目标C中的模运算符 [英] Modulo operator in Objective C
问题描述
从用目标C编程"(Kochan)中:
From the "Programing in Objective C" (Kochan):
程序5.8提示用户输入数字,然后继续显示数字 从该数字的最右边到最左边的数字.
Program 5.8 prompts the user to enter a number and then proceeds to display the digits from that number from the rightmost to leftmost digit.
// Program to reverse the digits of a number
#import <Foundation/Foundation.h>
int main (int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int number, right_digit;
NSLog (@"Enter your number.");
scanf ("%i", &number);
while ( number != 0 ) {
right_digit = number % 10;
NSLog (@"%i", right_digit);
number /= 10;
}
[pool drain];
return 0;
}
我的问题是:当用户输入1到9的单个数字时会发生什么?我找不到有关这种情况的任何材料. 编译后,程序只需继续返回那个数字即可.这是为什么? 我试图为此代码编写代码,并花了2个小时,试图为这个如果数字是个位数"问题合并循环和决策.解决方案是如此无知!
My question is: what happening when user types in single digit number- 1 to 9 ? I couldn't find any material about such case. After compilation the program just proceed with returning that single digit. Why is that? I was trying to come up with code for this task and spend literally 2 hours, trying to incorporate loops and decision making for this " if number is single digit" problem. And the solution was so ignorant!
推荐答案
取模后,模运算符将为您提供余数.如果yo有8%10,则结果为8,因为8/10为0,余数为8.如果您有38%10,则得到相同的结果,38/10为3,余数为8.
The modulo operator gives you the remainder after a division. If yo have 8 % 10 the result is 8 because 8 / 10 is 0 with a remainder of 8. You get the same result if you have 38 % 10, 38 / 10 is 3 with a remainder of 8.
模数是您通常在小学学习的第一门科目.有趣的是,大多数孩子的模数没有问题,但是当他们知道8/10为0.8时,他们对模数的理解就很困难.
edit: Modulo is what you normally learned as the first division in elemantary school. It is funny that the most children have no problem with modulo but when they learned that 8 / 10 is 0.8 they have problems understanding modulo.
这篇关于目标C中的模运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!