C ++类型转换问题 [英] C++ type converting issue

查看:140
本文介绍了C ++类型转换问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

#include <iostream>

using namespace std;

int aaa(int a) {
    cout << a * 0.3 << endl;
    return a * 0.3;
}

int main()
{
    cout << aaa(35000);
}

它输出:

10500
10499

我有一个解决方法来使用return a * 3/10;但我不喜欢。

I have a workaround to use "return a * 3 / 10;" but I don't like it.

编辑:

发现执行return float );给出预期值;

Found that doing "return float(a * 0.3);" gives expected value;

推荐答案

0.3 * 35000的结果是一个浮点数,略小于10500。被舍入到10500,但是当被强制转换为int时,舍去小数位数,得到10499。

The result of 0.3*35000 is a floating point number, just slightly less than 10500. When printed it is rounded to 10500, but when coerced into an int the fractional digits are discarded, resulting in 10499.

这篇关于C ++类型转换问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆