首页 > 解决方案 > 如果迭代次数太高 Mac 终端不输出

问题描述

如果我要求它迭代 3 次,代码可以正常工作,但这是最大值,之后终端不输出任何内容,只是保存会话。

编码:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main() {
  int i = 0 ;
  int n;
  int run;
  double d;
  double seed;
  double x;
  double y;
  double numx[run];
  double numy[run];
  double points[run];
  double sum;
  printf("Enter the seed for the random number generator: ");
  scanf("%lf", &seed);
  srand(seed);
  printf("Enter the number of iterations to run: ");
  scanf("%d", &run );
  for (i = 0; i < run; i++) {
    x = (double)rand()/RAND_MAX*2.0-1.0;
    printf(" x:%lf ", x*x);
    numx[i] = x*x;
  }
  printf("\n");
  i = 0;
  for (i = 0; i < run; i++) {
    y = (double)rand()/RAND_MAX*2.0-1.0;
    printf(" y:%lf ", y*y);
    numy[i] = y*y;
  }
  for (i = 0; i < run; i++){
    d = pow(numx[i]+ numy[i], 0.5);
    if (d <= 1.0){
      n += 1;
    }
  }
  printf("\n");
  printf("Number of points in circle: %d\n", n);

    return 0;
}

这是 3 次迭代时发生的情况:

Last login: Wed Oct 20 16:49:13 on ttys000
dhruvbishnoi@campus-031-248 ~ % /var/folders/yw/dq69cddx0ln9pwxkhnjpw_n40000gn/T/pi ; exit;
Enter the seed for the random number generator: 41      
Enter the number of iterations to run: 3
 x:0.998717  x:0.045754  x:0.920902 
 y:0.371260  y:0.471850  y:0.911363 
Number of points in circle: 1
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.

[Process completed]

这是 4 次迭代时发生的情况:

Last login: Wed Oct 20 16:49:27 on ttys000
dhruvbishnoi@campus-031-248 ~ % /var/folders/yw/dq69cddx0ln9pwxkhnjpw_n40000gn/T/pi ; exit;
Enter the seed for the random number generator: 41
Enter the number of iterations to run: 4
 x:0.998717  x:0.045754  x:0.920902  x:0.371260 
zsh: segmentation fault  /var/folders/yw/dq69cddx0ln9pwxkhnjpw_n40000gn/T/pi
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.

[Process completed]

当我告诉它迭代 5 次或更多次时会发生这种情况:

Last login: Wed Oct 20 16:50:20 on ttys000
dhruvbishnoi@campus-031-248 ~ % /var/folders/yw/dq69cddx0ln9pwxkhnjpw_n40000gn/T/pi ; exit;
Enter the seed for the random number generator: 41
Enter the number of iterations to run: 5
zsh: segmentation fault  /var/folders/yw/dq69cddx0ln9pwxkhnjpw_n40000gn/T/pi
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.

[Process completed]

这个问题可能是由于我的终端(Mac)引起的,因为我的其他项目也发生了类似的事情,但只是最近。

标签: macosterminalatom-editor

解决方案


您正在根据变量中的值创建许多数组,run但这样做时尚未为其分配值。在某些时候,这会导致您写入错误的地址。在您的情况下,似乎这一点是进入未初始化区域的 4 步。

一个快速的解决方法是以恒定大小创建数组,然后确保输入的值run小于常数。


推荐阅读