四舍五入到具体价值?

时间:2013-03-24 05:48:24

标签: ios objective-c

我需要围绕一个数字,让我们说543到数百或数十位。它可以是一个,因为它是游戏的一部分,这个阶段可以要求你做一个或另一个。

因此,例如,它可以询问“将数字舍入到最接近的数字”,如果数字为543,则必须输入540.

但是,我没有看到一个可以指定目标位置值来舍入的函数。我知道这是一个简单的解决方案,我现在想不出一个。

从我看到的情况来看,round函数舍入最后一个小数位?

由于

3 个答案:

答案 0 :(得分:7)

四舍五入到100的地方

NSInteger num=543;

NSInteger deci=num%100;//43
if(deci>49){
    num=num-deci+100;//543-43+100 =600
}
else{
    num=num-deci;//543-43=500
}

圆到10的地方

NSInteger num=543;

NSInteger deci=num%10;//3
if(deci>4){
    num=num-deci+100;//543-3+10 =550
}
else{
    num=num-deci;//543-3=540
}

修改: 试图将上述内容合并为一个:

NSInteger num=543;

NSInteger place=100; //rounding factor, 10 or 100 or even more.
NSInteger condition=place/2;

NSInteger deci=num%place;//43
if(deci>=condition){
    num=num-deci+place;//543-43+100 =600. 
}
else{
    num=num-deci;//543-43=500
}

答案 1 :(得分:1)

您可以在代码中使用算法:

例如,假设您需要将数字向上舍入到数百个位置。

int c = 543
int k = c % 100
if k > 50
   c = (c - k) + 100
else 
   c = c - k

答案 2 :(得分:1)

要对数字进行舍入,可以使用模数运算符%。

模数运算符为你提供除法后的余数。

因此543%10 = 3,543%100 = 43。

示例:

int place = 10;
int numToRound=543;
// Remainder is 3
int remainder = numToRound%place;
if(remainder>(place/2)) {
    // Called if remainder is greater than 5. In this case, it is 3, so this line won't be called.
    // Subtract the remainder, and round up by 10.
    numToRound=(numToRound-remainder)+place;
}
else {
    // Called if remainder is less than 5. In this case, 3 < 5, so it will be called.
    // Subtract the remainder, leaving 540
    numToRound=(numToRound-remainder);
}
// numToRound will output as 540
NSLog(@"%i", numToRound);

编辑:我的原始答案是在准备好之前提交的,因为我不小心点击了一个键来提交它。糟糕。

相关问题