我必须将一个数字四舍五入到最接近的整数。所以 4.3 将四舍五入为 4,4.7 将四舍五入为 5。中间有小数的数字(如 4.5)也将四舍五入为 5。我必须在不使用和“数学”的情况下进行此舍入。函数或“if 和 else 语句”。
问问题
21596 次
1 回答
19
The answer is pretty simple. Add 0.5 to the number and then cast it to an int. Like this:
int rounded = (int) (unrounded + 0.5);
This works because if the decimal part is less than 0.5, the integer part stays the same, and truncation gives the right result. If the decimal part is more that 0.5, the integer part increments, and again truncation gives what we want.
于 2013-09-09T00:43:35.293 回答