有人可以解释我这个代码吗?它给出与我们输入的数字相反
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);
}
我想了解这段代码是如何工作的。它为什么要做它所做的事情?如果我们输入 5123,它将给出 3215。如何?
C 系列语言的基础知识,运算符 % 在除以右侧参数时给出其左侧参数的其余部分。因此,n % 10
是十进制表示法中n
的最后一位数字(例如,3 表示 5123(。
长
话短说:
运算符
/
执行楼层除法:仅返回整数部分,不返回余数,运算符
%
返回除法操作的剩余部分
如果需要,下面是逐行说明。
long long n,i;
定义类型为long long
(64 位无符号整数(的变量n
和i
。
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
相关文章:
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 2D数组来自文本输入,中间有空格
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 如何在C++中读取空格分隔的输入 当我们不知道输入的数量时
- 如何输入数组的元素,每次获得新元素时,我们将其放在数组的中间?
- 如果我们在其中输入一个整数,则字符会给出整数作为输出,但是当分配给它一个整数时,这不会发生。为什么?
- 有人可以解释我这个代码吗?它给出与我们输入的数字相反
- 当我们声明 cin 为 int 并从 cin 中获取输入并在 cout 中打印 cin 时会发生什么?
- 当我们在以下程序(C )中输入字符时,该如何解决
- 我们可以在 c++ 中使用 vector 来获取未知大小的用户输入,直到我们按回车键
- 我们可以在两个输入之间获得时间吗?
- 为什么我们总是检查输入是否失败而不检查输出
- 如何创建一个模板类,该类具有两个变量,我们将从用户那里获取输入,并且输入值可以是任何类型的
- 我们应该使用哪种数据类型来输入一个介于 0<= 数字 <= 10^18 之间的数字
- 我们如何从霍尔效应传感器获得树莓派的模拟输入
- 如果我们在需要整数的开关情况下输入字符会发生什么
- 为什么我们不能在C++输入数组时输入向量?
- 为什么当我们从用户那里获得输入时我们需要一个缓冲区
- 嗨,我们在c++中有这个作业,它涉及到用户名和密码的输入
- 我们可以这样输入数组(a1,a2)吗?