在C ++中,float值被从double截断 [英] In C++ float value being truncated from double
问题描述
我以前使用float变量进行编码,从来没有遇到过这个问题.
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;
相对海峡前向代码
warning C4305: '=' : truncation from 'double' to 'float'
我了解数据被截断的想法(并且我也知道您可以在变量的末尾写入f
.但是,如果将变量声明为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.
我查询了其他一些票证,但它们与众不同,因此我的查询似乎找不到解决方案,即如果将数据声明为浮点数,为什么将其读取为double值.
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.
推荐答案
为什么编译器将文字值解释为双精度值
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
但是如果变量被声明为float ...
But if variables are declared as float...
表达式的类型从不依赖于表达式的使用方式.因此15.95
的类型均为double
,无论您做什么.如果需要,可以将类型转换为在较大的表达式中使用,这就是在这种情况下发出警告的原因.
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.
这篇关于在C ++中,float值被从double截断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!