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

后端 未结 9 1375
野的像风
野的像风 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:25

    In the case of the floating-point division, as long as one variable is of a floating-point datatype (float or double), then the other variable should be widened to a floating-point type, and floating-point division should occur; so there's no need to cast both to a float.

    Having said that, I always cast both to a float, anyway.

提交回复
热议问题