[英]Can someone explain me this code? It gives the reverse of the number we enter
#include <iostream>
using namespace std;
int main()
{
long long n,i;
cout << "Please enter the number:- \n";
cin >> n;
while (n!=0)
{
i=n%10; // what is the use of % here?
cout << i;
n=n/10;
}
return (1);
}
I want to understand how this code works.我想了解这段代码是如何工作的。 Why does it do what it does?
为什么它会做它所做的? If we enter 5123 it will give out 3215. How ?
如果我们输入 5123 它将给出 3215。如何?
The very basics of C family languages , operator % gives the remainder of its left hand side argument when divided by the right hand side one. C 系列语言的基础知识,运算符 % 给出其左侧参数的余数除以右侧参数。 So,
n % 10
is n
's last digit in decimal notation (for instance, 3 for 5123.)因此,
n % 10
是n
以十进制表示法的最后一位数字(例如,3 表示 5123。)
operator
/
performs floor division : only integer part returned, without remainder,运算符
/
执行地板除法:只返回整数部分,没有余数,operator
%
returns remainder of division operation运算符
%
返回除法运算的余数
long long n,i;
defines variables n
and i
of type long long
(64-bit unsigned integer).定义了
long long
(64 位无符号整数)类型的变量n
和i
。
cout << "Please enter the number:- \n";
prints out a prompt message hinting what is the expected input.打印出一条提示消息,提示预期的输入是什么。
cin >> n;
is a command waiting for standard input, that is saved in int variable n
.是一个等待标准输入的命令,它保存在 int 变量
n
。 Please note that invalid value (non-numeric) will cause an error later.请注意,无效值(非数字)稍后会导致错误。
while (n!=0)
starts a loop that would be terminated when/if n
becomes equal to zero.开始一个循环,当/如果
n
变得等于零时,该循环将被终止。
i=n%10; // what is the use of % here?
This command returns a remainder of division of value of variable n
by 10
.此命令返回变量
n
的值除以10
的余数。 The result of this operation is saved to variable i
.此操作的结果保存到变量
i
。 Eg例如
5123 % 10 = 3
512 % 10 = 2
51 % 10 = 1
5 % 10 = 5
Next,下一个,
cout << i;
prints the value of variable i
to stdout and keeps the cursor on same line, next column.将变量
i
的值打印到 stdout 并将光标保持在同一行的下一列。 Doing so in a loop it would print out each new value of variable i
in a single line, faking a reverse integer number.在循环中这样做,它将在一行中打印出变量
i
每个新值,伪造一个反向整数。
And, finally,最后,
n=n/10;
performs operation of "floor division" (division without remainder - returns integer part only) of value of variable n
by 10
.执行变量
n
的值除以10
的“整除法”(没有余数的除法 - 仅返回整数部分)运算。 Result is saved back to variable n
:结果被保存回变量
n
:
5123 / 10 = 512
512 / 10 = 51
51 / 10 = 5
5 / 10 = 0 // after this iteration the loop will terminate
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.