在C语言里如何用四舍五入把float变为int

如题所述

加与变量同符号的0.5,再强制取整就可以了。如下面的举例代码:

//#include "stdafx.h"//If the vc++6.0, with this line.
#include "stdio.h"
int main(void){
    double x=3.1415926,y=1.507,z=0.499999;
    printf("%d %d %d\n",int(x+(x>0?.5:-.5)),int(y+(y>0?.5:-.5)),int(z+(z>0?.5:-.5)));
    return 0;
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-03-22
float乘10,加5,强制转化成int,除10。 正数的。
负数的类似。本回答被提问者采纳
第2个回答  2012-03-22
直接把float加0.5转换成int就可以了
相似回答