【发布时间】:2015-02-16 09:10:58
【问题描述】:
如何对非浮点数进行四舍五入?例如9107609 降到 91 或者降到 911 等等。
【问题讨论】:
-
9107609/100000或9107609/10000 -
我明白了。非常感谢:)
如何对非浮点数进行四舍五入?例如9107609 降到 91 或者降到 911 等等。
【问题讨论】:
9107609/100000 或 9107609/10000
为了round,使用一半的加法(如果是正数,否则减去10000/2)
int rounded = (9107609 + 10000/2)/10000;
【讨论】:
#include <math.h>
//returns n rounded to digits length
int round_int (int n, int digits)
{
int d = floor (log10 (abs (n))) + 1; //number of digits in n
return floor(n / pow(10, d-digits));
}
【讨论】:
floor(number/(10^numberofdigitstocut)) 或 ceil(number/(10^numberofdigitstocut)) 之类的就可以了。
【讨论】:
分别除以 100000 或 10000。 C 除法向零舍入,因此数字将始终向下舍入。要四舍五入到最接近的整数,请参阅this question。
【讨论】: