[英]How to combine variables to represent scientific notation in C?
If I have 如果我有
a = 3;
b = 5;
How can I make it so that 我该怎么做
double result = 3e5, but only using variables? 双重结果= 3e5,但仅使用变量?
I know aeb won't work, obviously. 我知道aeb显然行不通。
Try: 尝试:
double result = a * pow(10.0,(double)b);
Or, with GNU extensions: 或者,使用GNU扩展:
double result = a * exp10((double)b);
In either case, #include math.h and link with the math library (eg. -lm
). 无论哪种情况,都#include math.h并链接到数学库(例如
-lm
)。 This is likely much more efficient than piecing together a string and converting to double. 这可能比将字符串拼凑在一起并转换为双精度要有效得多。
Use the function atof
defined in stdlib.h
and sprintf
: 使用
stdlib.h
和sprintf
定义的atof
函数:
float a = 3;
int b = 5;
char tmp[10];
sprintf(tmp, "%fe%d", a, b);
double x = atof(tmp);
printf("x = %fe%d = %f\n", a, b, x);
Output: http://ideone.com/NdDcNB 输出: http : //ideone.com/NdDcNB
x = 3.000000e5 = 300000.000000
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.