c++ double 截取,在C ++中,float值被从double截断

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: $" <

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.

解决方案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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值