我目前正在使用一个使用莱布尼兹求和计算 pi 值的 c 程序,但是一旦执行该程序,我就会在控制台中收到错误“段违规(‘核心’生成)”。我也检查过类似的问题,但我仍然无法将该信息放入我的问题中。这是我的代码:
#include <stdio.h>
double calPi(int x);
double calPi(int x)
{
double sum;
int i;
sum=0.0;
for (i=0; i<=x; i++)
{
if ((i=2)||((i%2)==0))
{
sum=sum+(1/(2*i+1));
}
else sum=sum-(1/(2*i+1));
}
return 4*sum;
}
int main(void)
{
int x;
double PI;
printf("Enter the number of terms you want to calculate");
scanf("%i",x);
PI=calPi(x);
printf("Pi value is: %f", PI);
system("pause");
return 0;
}
提前感谢您的任何提示、帮助或更正。
最佳答案
这是你的问题:
scanf("%i", x);
应该是
scanf("%i", &x);
您需要获取 x 的地址,否则仅使用 x 将被视为指向谁知道什么的指针。确保你在编译时打开警告,因为你的编译器应该警告你这样的事情。我的编译器提示
“格式字符串 '%i' 需要一个类型为 'int *' 的参数,但可变参数 1 的类型为 'int'”
关于c - 段冲突 (`core ' 生成)C 程序中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55552929/