簡體   English   中英

Output 數字反向 - c++

[英]Output numbers in reverse - c++

編寫一個程序,讀取整數列表,並反向輸出這些整數。 輸入以 integer 開頭,指示后面的整數個數。 為簡化編碼,在每個 output integer 后面加上一個空格,包括最后一個。 假設列表將始終包含少於 20 個整數。

輸入:5 2 4 6 8 10

預期 output:10 8 6 4 2

我的 output 是:

0 4196464 0 4196944 0 0 0 0 0 4197021 0 2 0 4196929 10 8 6 4 2

我在最后有答案,但我不知道如何擺脫前面的數字。 我猜它循環了 20 次,這就是為什么我的回答很奇怪。 我改變了我的最大值以適應輸入的數量,但這是我的作業作弊。

我的代碼:

#include <iostream>
using namespace std;

int main() {
  const int MAX_ELEMENTS = 20;  // Number of input integers
  int userVals[MAX_ELEMENTS];   // Array to hold the user's input integers
  int i;

  for (i = 0; i < MAX_ELEMENTS; ++i) {
    cin >> userVals[i];
  }
  for (i = MAX_ELEMENTS - 1; i >= 1; --i) {
    cout << userVals[i] << " ";
  }
  cout << endl;
  return 0;
}

你沒有按照你得到的指示,特別是這句話:

輸入以 integer 開頭,指示后面的整數個數。

正如您所推測的那樣,您確實正在讀取並打印出 20 個值,即使用戶實際上輸入的值更少(並且說明提供)。 給定的第一個數字指定后續數字的計數。 首先讀取該數字並將其存儲在一個變量中,然后您可以使用該變量來控制循環。

說到循環,您的 output 循環正在跳過數組的第一個元素。 循環條件需要是i >= 0而不是i >= 1

試試這個:

#include <iostream>
using namespace std;

int main() {
  const int MAX_ELEMENTS = 20;  // Number of input integers
  int userVals[MAX_ELEMENTS];   // Array to hold the user's input integers
  int i, count; // <-- ADD count!

  cin >> count; // <-- ADD THIS!

  for (i = 0; i < count; ++i) { // <-- use count, not MAX_ELEMENTS!
    cin >> userVals[i];
  }

  for (i = count - 1; i >= 0; --i) { // <-- use count, not MAX_ELEMENTS!
    cout << userVals[i] << " ";
  }

  cout << endl;
  return 0;
}

現場演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM