单精度和双精度铸造给出了不同的答案
Single-Precision and Double-Precision Casting Gives Different Answers
所以我有以下代码:
#include <iostream>
int main(){
float number = 0.6;
int anotherNumber = 20;
int value = (int) ((float) anotherNumber * number);
std::cout << value;
std::cin.get();
}
它给出了12,就像它应该考虑20 * 0.6 = 12。但是,如果我将所有浮点数改为双精度:
#include <iostream>
int main(){
double number = 0.6;
int anotherNumber = 20;
int value = (int) ((double) anotherNumber * number);
std::cout << value;
std::cin.get();
}
结果是11。让事情变得更奇怪的是,如果我改变代码,让值先存储在一个变量中,然后才存储,它又给出了正确的答案(12)。
#include <iostream>
int main(){
double number = 0.6;
int anotherNumber = 20;
double intermediate = (double) anotherNumber * number;
int value = (int) intermediate;
std::cout << value;
std::cin.get();
}
这到底是怎么回事?
0.6
不能精确地用任何二进制浮点格式表示。根据数据类型,它有时大一些,有时小一些。请参阅每个程序员都应该知道的关于浮点算术的详细说明。
"存储在内存中"版本是不同的,因为x87 FPU内部使用80位浮点寄存器。
编辑:详细计算:
float 0.6 in memory;
.100110011001100110011010
loaded to register:
.10011001100110011001101000000000000000000000000000000000000000000
multiplied by 20:
1100.0000000000000000000010000000000000000000000000000000000000000
rounded down:
1100
double 0.6 in memory
.10011001100110011001100110011001100110011001100110011
loaded to register:
.10011001100110011001100110011001100110011001100110011000000000000
multiplied by 20:
1011.1111111111111111111111111111111111111111111111111110000000000
rounded down:
1011
double 0.6 in memory
.10011001100110011001100110011001100110011001100110011
loaded to register:
.10011001100110011001100110011001100110011001100110011000000000000
multiplied by 20:
1011.1111111111111111111111111111111111111111111111111110000000000
converted to double-precision and stored to memory:
1100.0000000000000000000000000000000000000000000000000
loaded to register:
1100.0000000000000000000000000000000000000000000000000000000000000
rounded down:
1100
相关文章:
- 欧拉项目#8答案是大以获得有效答案
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 首要问题的答案让值班员搞错了
- 正在将csv文件读取为双精度矢量
- 如何理解将半精度指针转换为无符号长指针和相关的内存对齐
- 我可以信任表示整数的浮点或双精度来保持精度吗
- 如何在C++中的同一函数中使用字符串和双精度
- 特征::矩阵<双精度,1,3> 结构类型函数中的返回类型函数
- C++问题:用户认为数字1-100,程序提出问题不超过6次即可得到答案。无法正确
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- 如何计算具有指定类型的表达式的相对精度和绝对精度
- 如何打印boost多精度128位无符号整数
- 我试图制作一个程序,要求用户输入问题和答案,但程序循环不正确
- 检查是否以特定精度给出双精度
- 转换函数,将 std::数组的双精度作为参数或双精度作为参数单独转换
- C 字符串返回字符串的整数/双精度/长整型值
- 将当前时间 simTime.dbl() 与以前存储的双精度值进行比较并不总是给出正确的答案......为什么?
- 单精度和双精度铸造给出了不同的答案
- 为什么双精度和长双精度给出不同的答案?