C语言 为什么 printf 不使用科学记数法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21287974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why is printf not using scientific notation?
提问by Simon.
I understand that this is a common problem. However I can't find a solid straight answer.
我了解这是一个常见问题。但是我找不到一个可靠的直接答案。
16 ^ 54 = 1.0531229167e+65 (this is the result I want)
When I use pow(16,54), I get:
当我使用时pow(16,54),我得到:
105312291668557186697918027683670432318895095400549111254310977536.0
105312291668557186697918027683670432318895095400549111254310977536.0
Code is as follows:
代码如下:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
void main(){
double public;
double a = 16;
double b = 54;
public = (pow(a,b));
printf("%.21f\n", public);
}
Code executed with:
代码执行:
gcc main.c -lm
gcc main.c -lm
What I'm doing wrong?
我做错了什么?
回答by dasblinkenlight
What am I doing wrong?
我究竟做错了什么?
Several things:
几件事:
- Use
%.10eformat for scientific notation withprintffor a printout with ten digits after the dot, - Return an
intfrom yourmain, - Consider not using
publicto name a variable, on the chance that your program would need to be ported to C++, wherepublicis a keyword.
- 使用
%.10e科学记数法格式,printf打印点后有十位数字, - 返回一个
int从你的main, - 考虑不使用
public命名变量,因为您的程序需要移植到 C++,其中public是关键字。
Here is how you can fix your program:
以下是修复程序的方法:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main(){
double p;
double a = 16;
double b = 54;
p = (pow(a,b));
printf("%.10e\n", p);
return 0;
}
回答by abelenky
Have you tried:
你有没有尝试过:
printf("%e\n", public);
The %especifier is for scientific notation, as described in the documentation
该%e说明符是科学记数法,如文档中所述
回答by Shafik Yaghmour
If you need scientific notation you need to use the %eformat specifier:
如果您需要科学记数法,则需要使用%e格式说明符:
printf("%e\n", public);
^^
Also, publicis a keywordin C++ and so it would be a good idea to avoid that and any other keywordsin case this code needs to be portable.
此外,public是C++ 中的关键字,因此最好避免使用该关键字和任何其他关键字,以防此代码需要可移植。

