我以前使用浮点变量进行编码,但从未遇到过这个问题。
float a, b, subtotal, stx;
a=15.95;
b=24.95;
subtotal=a+b;
stx=subtotal*.07;
cout << "Item 1: $" << a << endl;
cout << "Item 2: $" << b << endl;
cout << "\nSubtotal: $" <<subtotal<< endl;
cout << "Sales Tax: $" << stx << endl;
cout << "Total: $" << subtotal+stx << endl;
相对简单的前向代码
warning C4305: '=' : truncation from 'double' to 'float'
我理解数据被截断的想法(我也知道你可以在变量的末尾写上 f
。但是如果变量被声明为 float 为什么编译器解释文字如果它被声明为 float ,则值作为 double 。
我查了其他几张票,它们与我的查询不同我似乎无法找到解决方案来解释为什么数据被声明为 float 时被读取为 double 。
最佳答案
why is the compiler interpreting the literal values as as doubles
因为这就是文字的解释方式,除非您添加修饰符来指定不同的类型。
a=15.95f;
^ gives the literal "float" type
But if variables are declared as float...
表达式的类型从不取决于表达式的使用方式;所以 15.95
的类型是 double
无论你用它做什么。如有必要,类型会转换为在更大的表达式中使用,这就是在这种情况下发出警告的原因。
关于c++ - 在 C++ 中,float 值被从 double 中截断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28635257/