为什么printf没有使用科学记数法?
我知道这是一个常见的问题。 但是我找不到一个可靠的直接答案。
16 ^ 54 = 1.0531229167e+65 (this is the result I want)
当我使用pow(16,54)
,我得到:
105312291668557186697918027683670432318895095400549111254310977536.0
代码如下:
#include #include #include void main(){ double public; double a = 16; double b = 54; public = (pow(a,b)); printf("%.21f\n", public); }
执行代码:
gcc main.c -lm
我做错了什么?
我究竟做错了什么?
几件事:
- 使用
%.10e
格式的科学记数法,printf
用于点后10位数的打印输出, - 从你的
main
回来一个int
, - 考虑不使用
public
命名变量,因为您的程序需要移植到C ++,其中public
是关键字。
以下是修复程序的方法:
#include #include #include int main(){ double p; double a = 16; double b = 54; p = (pow(a,b)); printf("%.10e\n", p); return 0; }
在ideone上演示。
你有没有尝试过:
printf("%e\n", public);
%e
说明符用于科学记数法,如文档中所述
如果您需要科学记数法,则需要使用%e
格式说明符 :
printf("%e\n", public); ^^
此外, public
是C ++中的关键字 ,因此,如果此代码需要可移植,最好避免使用该关键字和任何其他关键字 。