在 C 中将整数四舍五入到最接近的十或百 [英] Rounding integers to nearest ten or hundred in C
问题描述
我想用 C 语言编写一个满足以下条件的函数:
I'm trying to think of a function in C that would satisfy the following conditions:
- 它接受一个大于 0 的整数作为参数;
- 它将整数向上舍入到最接近的值,以便只有第一个数字不是零
例如:
53 变成 60..
197 变成 200..
197 comes out as 200..
4937 的结果是 5000..
4937 comes out as 5000..
有没有办法做到这一点,无论尾随零的数量如何,都满足要求?
Is there a way to do this so that the requirement is satisfied regardless of the number of trailing zeroes?
例如,我了解我可以在任何个别情况下如何做到这一点.将 53 除以 10 然后将 ceil() 乘以 10,
但我想要一个可以处理任何值的.
For example, I understand how I could do it in any individual case. divide 53 by 10 then ceil(), multiply by 10,
but I would like one that can handle any value.
意见?想法?
推荐答案
没有必要将数字转换为字符串并返回.您可以使用基本的模运算和乘除法来完成此操作.
It's unnecessary to convert the number to a string and back. You can do this using basic modulo arithmetic and multiplication and division.
这是一个纯数字解决方案,希望在运行时间方面更有效:
Here's a pure numeric solution, hopefully somewhat more efficient in terms of running time:
int round_up_to_max_pow10(int n)
{
int tmp = n;
int i = 0;
while ((tmp /= 10) >= 10) {
i++;
}
if (n % (int)(pow(10, i + 1) + 0.5)) {
tmp++;
}
for (; i >= 0; i--) {
tmp *= 10;
}
return tmp;
}
printf("Original: %d; rounded: %d\n", 4937, round_up_to_max_pow10(4937));
这篇关于在 C 中将整数四舍五入到最接近的十或百的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!