C语言中的Pi
Pi in C language
所以我试图在 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"
。将 "%lf"
用于 long double
会导致未定义的行为。
#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的评论
使用 printf
中的默认设置,很难看出使用 float
、double
和 long double
表示数字的准确程度。通过使用在小数点后打印更多数字的格式,差异会更清楚。
程序:
#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 (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
谢谢
要打印 long double
,请使用 "%Lf"
。将 "%lf"
用于 long double
会导致未定义的行为。
#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的评论
使用 printf
中的默认设置,很难看出使用 float
、double
和 long double
表示数字的准确程度。通过使用在小数点后打印更多数字的格式,差异会更清楚。
程序:
#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