gpt4 book ai didi

c++ - "double"不打印小数

转载 作者:太空宇宙 更新时间:2023-11-03 10:30:06 26 4
gpt4 key购买 nike

我想知道为什么在这个程序中,“pi_estimated”不会打印为带小数位的数字,尽管变量被声明为“double”。但是,它会打印出一个整数。

double get_pi(double required_accuracy)
{
double pi_estimation=0.0;
int x,y;
double p=0.0,q=0.0,r=0.0;
int D=0;
for(int N=1;N<=1e2;N++)
{
x = rand()%100;
p = (x/50.0 - 1.0)/100.0;
y = rand()%100;
q = (y/50.0 - 1.0)/100.0;
r = p*p + q*q;
if((sqrt(r))<1.0)
{
D++;
pi_estimation = 4.0*(double (D/N));
}
if(double (4/(N+1)) < (required_accuracy*pi_estimation/100.0))
{
cout<<pi_estimation<<endl;
return (pi_estimation);
}
}
}

int main()
{
double pi_approx=0.0, a, actual_accuracy=0.0;
for(a=0.1;a>=1e-14;a/=10)
{
pi_approx = get_pi(a);
actual_accuracy = (fabs((pi_approx - M_PI)/(M_PI)))*100.0;
cout<<actual_accuracy<<endl;
}
}

最佳答案

这一行是罪魁祸首:

pi_estimation = 4.0*(double (D/N));

因为DN都是intD/N是一个int。将 int 转换为 double 不能神奇地让小数凭空出现。

这是固定的行:

pi_estimation = 4.0 * (((double) D) / N));

你也可以先乘法,这样就不需要那么多括号了:

pi_estimation = 4.0 * D / N;

D 乘以 4.0,因此它变成了 double 因为 double * int = double。然后除以 N。由于 (x * y)/z === x * (y/z)(关联属性),表达式是等价的。

关于c++ - "double"不打印小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19306004/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com