有人可以解释我这个代码吗?它给出与我们输入的数字相反

Can someone explain me this code? It gives the reverse of the number we enter

本文关键字:我们 输入 数字 解释 代码      更新时间:2023-10-16
#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);

}

我想了解这段代码是如何工作的。它为什么要做它所做的事情?如果我们输入 5123,它将给出 3215。如何?

C 系列语言的基础知识,运算符 % 在除以右侧参数时给出其左侧参数的其余部分。因此,n % 10是十进制表示法中n的最后一位数字(例如,3 表示 5123(。

话短说:

运算符/执行楼层除法:仅返回整数部分,不返回余数,

运算符%返回除法操作的剩余部分

如果需要,下面是逐行说明。

long long n,i;

定义类型为long long(64 位无符号整数(的变量ni

cout << "Please enter the number:- n";

打印出一条提示消息,提示预期的输入是什么。

cin >> n;

是等待标准输入的命令,保存在 int 变量n中。 请注意,无效值(非数字(稍后会导致错误。

while (n!=0)

启动一个循环,当/如果n变为零时终止。

i=n%10;   // what is the use of % here? 

此命令返回变量n的值除以10的余数。 此操作的结果将保存到变量i中。 例如

5123 % 10 = 3
512 % 10 = 2
51 % 10 = 1
5 % 10 = 5

下一个

cout << i;

将变量i的值打印到 stdout,并将光标保持在同一行,下一列。在循环中这样做,它将在一行中打印出变量i的每个新值,伪造一个反向整数。

最后,

n=n/10;

执行变量n值的"地板除法"(无余数除法 - 仅返回整数部分(的操作10。结果保存回变量n

5123 / 10 = 512
512 / 10 = 51
51 / 10 = 5
5 / 10 = 0    // after this iteration the loop will terminate
相关文章: