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

后端 未结 4 1405
清酒与你
清酒与你 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 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(340)/101;
    

    or just use a floating literal:

    result = 340.0f/101;
    

提交回复
热议问题