In C++ float value being truncated from double

倖福魔咒の 提交于 2019-12-04 06:13:12

问题


I've coded using float variables before and never had this problem.

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;

relatively strait forward code

warning C4305: '=' : truncation from 'double' to 'float'

I understand the idea of data being truncated (and I also know that you can write the f at the end of the variable. But if variables are declared as float why is the compiler interpreting the literal values as as doubles if it was declared as floats.

I looked up a few other tickets and they were different then my inquiry I can't seem to find a solution as to why the data is being read as a double if its declared as a float.


回答1:


why is the compiler interpreting the literal values as as doubles

Because that's how literals are interpreted, unless you add modifiers to specify a different type.

a=15.95f;
       ^ gives the literal "float" type

But if variables are declared as float...

The type of an expression never depends on how the expression is used; so 15.95 has type double whatever you do with it. The type is converted for use in a larger expression, if necessary, and that's what gives the warning in this case.




回答2:


15.95 is treated as a double no matter what it is assigned to; the variable's type only affects what value it ends up holding, not what you try to assign to it. The right side of an assignment is always evaluated first.




回答3:


The processes the string tokens that make up your code - it sees is "2.7" or 15.95, which is numeric (starts with a digit) and floating point (has a .) The default container for floating point numbers is a double (otherwise you'd get really erroneous outcomes for most of the hard coded numbers you enter. After the value of the expression is evaluated (in this case, just the value itself), it's assigned to a float value, which isn't precise enough to store the result, hence the warning.




回答4:


From standard 2.14.4

The type of a floating literal is double unless explicitly specified by a suffix.

(emphasis mine)



来源:https://stackoverflow.com/questions/28635257/in-c-float-value-being-truncated-from-double

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!