默认C++float转换成int
是直接去除小数点后边的数字
float
转换为 int
:9.34 = (int) 9;9.99 = (int) 9
#include<stdio.h>
int main()
{
float i = 9.34;
float j = 9.99;
int a, b;
a = (int) i;
b = (int) j;
printf("a = %d\n",a);
printf("b = %d\n",b);
}
上面的输出结果为:
a = 9
b = 9
float
转换为 int
需要四舍五入提高精度,则基本算法如下:round()
函数转换后虽然数值小数点后都变为了零,但此时还是float
,还需要转换为int
。#include<stdio.h>
int main()
{
float zer = 0;
float i = 9.34;
float j = 9.99;
float k = -9.34;
float m = -9.99;
int a, b, c,