将整型转换为双精度

Conversion of integer to double

本文关键字:双精度 转换 整型      更新时间:2023-10-16

我需要确定一组输入的标准差。这需要求和(每个输入-均值)^2。我有以下代码来执行此操作(510是用于测试的示例输入):

int testDiff = 510;       
console.printf("testDiff = %i rn",testDiff);
double testDiff_double = static_cast<double>(testDiff);
console.printf("testDiff_double = %d rn",testDiff_double);
double result = pow(static_cast<double>(testDiff),2);
console.printf("result = %d rn",result);

但是,这段代码没有生成预期的输出(260100)。如果打印每个阶段获得的值,将得到如下结果:

testDiff = 510
testDiff_double = 0
pow = 0

为什么从整数到双失败的转换?我正在使用static_cast,因此如果转换存在逻辑问题,我预计在编译时将出现错误。

注意(虽然它不应该重要):我在MBED微控制器上运行此代码。

因为您使用%d而不是%f来显示浮点值

在您的printf函数中,尝试使用%f而不是%d。

您必须使用%f%e%E%g才能显示双/浮点数。

来自printf参考页面:

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.