如果迭代次数太高,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: %dn", 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)引起的,因为类似的事情已经发生在我的其他项目中,但只是最近。

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

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

相关内容

  • 没有找到相关文章

最新更新