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

后端 未结 4 1400
清酒与你
清酒与你 2021-01-23 01:03
#include

using namespace std;

int main(int argc, char** argv){
        float result;
        result=(340/101);
        cout<<\"Result=\"<

        
相关标签:
4条回答
  • 2021-01-23 01:57

    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 讨论(0)
  • 2021-01-23 02:00

    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;
    
    0 讨论(0)
  • 2021-01-23 02:05

    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.

    0 讨论(0)
  • 2021-01-23 02:07

    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)
    
    0 讨论(0)
提交回复
热议问题