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

后端 未结 4 1413
清酒与你
清酒与你 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;

提交回复
热议问题