开发者

Why result output is integer even result is defined as float?

开发者 https://www.devze.com 2023-02-10 19:44 出处:网络
#include<iostream> using namespace std; int main(int argc, char** argv){ float result; result=(340/101);
#include<iostream>

using namespace std;

int main(int argc, char** argv){
        float result;
        result=(340/101);
        cout<&l开发者_运维百科t;"Result="<<result;

}

in this code result is=3, i'm curious about why is that? what is the prevention of this cause and it can be seen a minor problem but it really deprecate my results in my data analysis program.

EDIT: thanks for the answers, i was trying the code below and it also gives me 3, so that's why i confused now i'm clear.

result=(float)(340/101);

Thanks all


Because the expression (340/101) is evaluated independent of its surrounding context. int/int always results in an int. It makes no difference if you store that int in a float variable later on.


340 is an integer and 101 is an integer, so 340/101 performs integer division. The result of the division is converted to a float when it is assigned to result.

You need to cast one to a floating point type to have floating point division performed:

result = static_cast<float>(340)/101;

or just use a floating literal:

result = 340.0f/101;


It's due to integer division, as both operands in the division operation are integers. Either cast one of the numbers to a float, or utilize floating point syntax:

result = (340.0 / 101.0)


In C++, the (340/101) is considered in isolation. Since both operands of / are ints, the compiler generates code for integer division. Then, since you're assigning that result to a float, it generates code to convert the resulting int to float.

To get floating point division, you need to ensure that (at least) one of the operands to / starts out as a float (or double), such as: float result = 340.0f / 101.0f;

0

精彩评论

暂无评论...
验证码 换一张
取 消