21xrx.com
2024-09-20 00:38:20 Friday
登录
文章检索 我的文章 写文章
C++程序:输入12345,输出1 2 3 4 5
2023-07-05 08:50:10 深夜i     --     --
C++ 输入 输出 12345 空格分隔

在C++中,我们可以使用循环语句来从输入流中读取一个数,然后将该数的每个位倒序输出来。下面给出实现细节。

1. 读入整数

我们首先使用cin读入一个整数。假设这个数是n。

2. 取出每个位

从数字最后一位开始,我们使用%运算符取出每位数的值,并将其存储在一个容器中。由于我们需要逆序输出这些数,我们使用了一个vector来存储。

代码如下:


int n;

vector<int> digits;

cin >> n;

while (n != 0) {

  digits.push_back(n % 10);

  n /= 10;

}

3. 输出每个位

现在我们可以逆序输出容器中的每个元素。我们可以使用auto关键字或者迭代器来遍历容器中的元素。

代码如下:


for (auto it = digits.rbegin(); it != digits.rend(); ++it) {

  cout << *it << " ";

}

完整代码:


#include <iostream>

#include <vector>

using namespace std;

int main() {

  int n;

  vector<int> digits;

  cin >> n;

  while (n != 0) {

    digits.push_back(n % 10);

    n /= 10;

  }

  for (auto it = digits.rbegin(); it != digits.rend(); ++it) {

    cout << *it << " ";

  }

  cout << endl;

  return 0;

}

运行结果:

输入:12345

输出:1 2 3 4 5

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复