macos - 如果迭代次数太高 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)引起的,因为我的其他项目也发生了类似的事情,但只是最近。
解决方案
您正在根据变量中的值创建许多数组,run
但这样做时尚未为其分配值。在某些时候,这会导致您写入错误的地址。在您的情况下,似乎这一点是进入未初始化区域的 4 步。
一个快速的解决方法是以恒定大小创建数组,然后确保输入的值run
小于常数。
推荐阅读
- angular - 如何以 Angular 形式设置 RxJS 的默认值
- java - 检查 Firebase 数据库中存在的所有节点中的特定值
- c++ - 对于 char d,执行 cout << &d 时出现奇怪的输出
- javascript - 使用 sinon 监视类方法的参数
- swift - 使图像滑动并重新调整到容器内的原始位置。自定义滑块快速
- unix - 如何在匹配 #1 后找到的行中替换匹配的文本(匹配 #2)
- javascript - 为什么在 collection.replaceOne 之后我的 res.statusCode 从 200 变为 404?
- python - 扩展 3D 阵列
- c# - Flurl 数组编码
- php - 单击缩略图时动态php缩放图像