C++中,float a;int b,c;咋样才能使a=b/c的结果显示为小数

来源:百度知道 编辑:UC知道 时间:2024/05/08 09:31:28

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

b/c因为b、c都是int型,所以按整形来计算了。

a=(float)b/c

赞成当然也可以写成
(float)b/(float)a

C++ Suggests to use static_cast<float> to perform this conversion.

This conversion is safer than "(float)a/c"(or float(a/c)), and this conversion is a C++ style conversion, the "(float)a/c" method is old C style conversion.

/*if float and int is incompatible, a gets a null pointer, but old C style conversion doesn't.*/
a = static_cast<float>(b/c);