Ios 四舍五入到特定值?
我需要把一个数字四舍五入,比如说543到百位或十位。它可以是其中之一,因为它是游戏的一部分,这个阶段可以要求你做一个或另一个 例如,它可以问“将数字四舍五入到最接近的十位”,如果数字是543,他们就必须输入540 但是,我看不到一个可以指定要舍入的目标位置值的函数。我知道有一个简单的解决办法,但我现在想不出一个 在我看来,Ios 四舍五入到特定值?,ios,objective-c,Ios,Objective C,我需要把一个数字四舍五入,比如说543到百位或十位。它可以是其中之一,因为它是游戏的一部分,这个阶段可以要求你做一个或另一个 例如,它可以问“将数字四舍五入到最接近的十位”,如果数字是543,他们就必须输入540 但是,我看不到一个可以指定要舍入的目标位置值的函数。我知道有一个简单的解决办法,但我现在想不出一个 在我看来,round函数将最后一位小数舍入 谢谢您可以在代码中使用算法: 例如,假设您需要将一个数字四舍五入到百位 int c = 543 int k = c % 100 if k &g
round
函数将最后一位小数舍入
谢谢您可以在代码中使用算法: 例如,假设您需要将一个数字四舍五入到百位
int c = 543
int k = c % 100
if k > 50
c = (c - k) + 100
else
c = c - k
四舍五入到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
}
要对数字进行四舍五入,可以使用模数运算符% “模”操作符提供除法后的余数 所以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);
int-place=10;
int numToRound=543;
//余数是3
整数余数=numToRound%位置;
如果(余数>(位置/2)){
//如果余数大于5,则调用。在本例中,余数为3,因此不会调用此行。
//减去余数,然后四舍五入10。
numToRound=(numToRound余数)+位置;
}
否则{
//如果余数小于5,则调用。在本例中,3小于5,因此将调用它。
//减去余数,留下540
numToRound=(numToRound余数);
}
//numToRound将输出为540
NSLog(@“%i”,numToRound);
编辑:我的原始答案是在准备好之前提交的,因为我不小心按了一个键提交了它。哎哟。我无法清楚地理解您的问题:(@iPatel)我添加了一个示例。您可能希望将逻辑更新为num=num deci+10;以便四舍五入到10的位代码。