将整型转换为双精度
Conversion of integer to double
我需要确定一组输入的标准差。这需要求和(每个输入-均值)^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.
相关文章:
- 为什么将双精度转换为 int 似乎在第 16 位数字之后将其四舍五入?
- 在 c++ 中从双精度转换为字符串
- 使用 sprintf 和 %g 将双精度转换为字符串的意外结果
- 从双精度转换为整数的显式类型是否始终检查整数溢出?
- C++,遇到将双精度转换为整数的问题
- 在C++中将双精度转换为intptr_t
- 将大双精度转换为科学记数法以用作字符串?
- 了解双精度转换与整数转换中的整数与截断关系
- 将 OLE 自动化日期 (OADate) 双精度转换为结构 tm,而不使用 VariantTime到SystemTime
- 无法在赋值中将"双精度 (*)[4]"转换为"双精度**"
- 将大双精度转换为无符号 int 期间堆栈损坏
- 将双精度转换为本地8位
- 警告从"双精度"转换为"int"
- 如何将双精度转换为浮点指针
- 将双精度转换为整数时出错
- 使用并集将双精度转换为十六进制再转换为双精度
- 是否有可以将每个双精度转换为唯一uint64_t,保持精度和顺序的功能?(为什么我找不到?
- 使用定点表示法将双精度转换为字符串,没有尾随零和机智的冲刺
- 在C++中将双精度转换为字符*/字符串
- 无法将双精度 [] [] 转换为双精度 **