Which variables should I typecast when doing math operations in C/C++?

后端 未结 9 1368
野的像风
野的像风 2020-12-02 23:41

For example, when I\'m dividing two ints and want a float returned, I superstitiously write something like this:

int a = 2, b = 3;
float c = (float)a / (floa         


        
9条回答
  •  失恋的感觉
    2020-12-03 00:31

    I think as long as you are casting just one of the two variables the compiler will behave properly (At least on the compilers that I know).

    So all of:

    float c = (float)a / b;

    float c = a / (float)b;

    float c = (float)a / (float)b;

    will have the same result.

提交回复
热议问题