gpt4 book ai didi

c - C语言中的圆周率

转载 作者:行者123 更新时间:2023-11-30 18:38:44 24 4
gpt4 key购买 nike

所以我试图在c(IDE = DEV C++)中获取pi的值,所以我在其中使用long double,它给我的结果是一组完整的零这是程序

int main() 
{
long double rootOf3;

rootOf3 = (22.0/7.0);

printf("%lf", rootOf3);
system("pause");
return 0;
}

之后我发现 pi 的值在 c 中并不精确,并且已经在 math.h 中声明,当我尝试使用此代码获取该值时

int main() 
{

printf("%f", M_PI);
printf("%e", M_PI);
printf("%lf", M_PI);
system("pause");
return 0;
}

我得到了这些值

3.1415933.141593e+0003.141593Press any key to continue . . .

所以我的问题

1)第一个程序中的错误是什么?我可以使用上面的代码使用 long double 获取 pi 的值
2)在c中,pi的值是否不准确?为什么我没有得到math.h中分配的整个pi值

谢谢

最佳答案

要打印long double,请使用"%Lf"。对 long double 使用 "%lf" 会导致未定义的行为。

#include <stdio.h>

int main()
{
long double pi = 22.0/7.0;
printf("%Lf\n", pi);
printf("%lf\n", pi);
return 0;
}

输出:

3.142857
0.000000

更新,回应OP的评论

使用中的默认设置,很难看出使用floatdoublelong double表示数字的准确度> printf 。通过使用在小数点后打印更多数字的格式,差异会更明显。

程序:

#include <stdio.h>

void test1()
{
float pi = 22.0f/7.0;
printf("=== float ================\n");
printf("%.25lf\n", pi);
printf("%lf\n", pi);
}

void test2()
{
double pi = 22.0/7.0;
printf("=== double ===============\n");
printf("%.25lf\n", pi);
printf("%lf\n", pi);
}

void test3()
{
long double pi = 22.0L/7.0;
printf("=== long double ==========\n");
printf("%.25Lf\n", pi);
printf("%Lf\n", pi);
}

int main(void)
{
test1();
test2();
test3();
return 0;
}

输出:

=== float ================
3.1428570747375488281250000
3.142857
=== double ===============
3.1428571428571427937015414
3.142857
=== long double ==========
3.1428571428571428572357888
3.142857

关于c - C语言中的圆周率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32794125/

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