我需要确定一组输入的标准偏差。这需要(每个输入 - 平均值)^ 2的总和。我有以下代码来执行此操作(510是用于测试的示例输入):
int testDiff = 510;
console.printf("testDiff = %i \r\n",testDiff);
double testDiff_double = static_cast<double>(testDiff);
console.printf("testDiff_double = %d \r\n",testDiff_double);
double result = pow(static_cast<double>(testDiff),2);
console.printf("result = %d \r\n",result);
但是,此代码不会生成预期输出(260100)。如果我打印在每个阶段获得的值,我会得到以下结果:
testDiff = 510
testDiff_double = 0
pow = 0
为什么从整数到双精度的转换失败?我正在使用static_cast,所以如果转换存在逻辑问题,我在编译时会遇到错误。
注意(虽然没关系):我在MBED微控制器上运行此代码。
答案 0 :(得分:2)
因为您使用%d
而不是%f
来显示浮点值。
答案 1 :(得分:2)
在printf函数中,尝试使用%f而不是%d。
答案 2 :(得分:1)
您必须使用%f
或%e
或%E
或%g
才能显示双/浮点数。
c Character
d or i Signed decimal integer
e Scientific notation (mantise/exponent) using e character
E Scientific notation (mantise/exponent) using E character
f Decimal floating point
g Use the shorter of %e or %f
G Use the shorter of %E or %f
o Unsigned octal
s String of characters
u Unsigned decimal integer
x Unsigned hexadecimal integer
X Unsigned hexadecimal integer (capital letters)
p Pointer address
n Nothing printed. The argument must be a pointer to a signed int, where the number of characters written so far is stored.
% A % followed by another % character will write % to stdout.