这是一个根据“任意两个整数互质的概率为 6/π2”这一事实计算 Pi 值的程序。该程序编译成功,但当我尝试运行它时,出现错误:
Segmentation fault (core dumped)
我试图将 for 循环中的条件语句更改为 i < 9999。通过这样做,程序给出的输出在 3.000000、3.162278 和段错误(核心已转储)之间变化(每次运行时)。
我只想使用上述属性计算 π 的值。请帮忙。
此外,请帮助我选择一个更好的生成随机数的函数,并建议我进行一些代码改进。谢谢。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
int gcd(int a, int b)
{
// Everything divides 0
if (a == 0 || b == 0)
return 0;
// base case
if (a == b)
return a;
// a is greater
if (a > b)
return gcd(a-b, b);
return gcd(a, b-a);
}
int main()
{
srand(time(0));
int numberOne = rand();
int numberTwo = rand();
int coprime = 0;
for(int i = 0; i < 99999; i++)
{
numberOne = rand();
numberTwo = rand();
if(gcd(numberOne, numberTwo) == 1)
{
coprime++;
}
}
// co-prime/99999 = 6 / pi^2
double pi = 599994/coprime;
pi = sqrt(pi);
printf("%f\n", pi);
return 0;
}
最佳答案
OP 的 gcd()
递归太深,导致 堆栈溢出。 @OldProgrammer
考虑一个更高效的替换递归函数
做除法时使用 FP 数学
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
unsigned gcdu(unsigned a, unsigned b) {
return (b == 0) ? a : gcdu(b, a % b);
}
int main(void) {
srand(time(0));
int numberOne = rand();
int numberTwo = rand();
int coprime = 0;
for (int i = 0; i < 99999; i++) {
numberOne = rand();
numberTwo = rand();
if (gcdu(numberOne, numberTwo) == 1) {
coprime++;
}
}
// double pi = 599994 / coprime;
double pi = 1.0*599994 / coprime; //Insure FP division
pi = sqrt(pi);
printf("%f\n", pi);
return 0;
}
输出
3.142940
关于c++ - Pi 计算器程序每次运行时都会给出不同的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47909019/