我試圖解決我收到的任務表上的一個問題,以幫助我進一步瞭解我的課程中的C++代碼。如何檢查輸入數字的次數
的問題是(我引述):
寫一個程序:
- 要求用戶輸入1和5之間10個號碼爲一個陣列並在屏幕上顯示陣列
- 創建第二個大小爲5的數組,並用零填充
- 計算第一個數組中已輸入多少個1s,2s,... 5s並將此數字存儲在第二個數組中。
- 顯示第二個數組,如下例所示。
問題是如何去檢查數字輸入的次數。我正在考慮一個for
循環,但是我寫這個循環的方式根本上是不正確的,所以我發現自己正在努力看到我所遇到的錯誤。也許我錯過了一些簡單的東西?任何幫助都會很棒。
這是我的(可怕的)for
循環嘗試,所以你可以看到我的錯誤。
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
int input[10];
const int MAX_NO = 5;
int COUNT[5] = { 0,0,0,0,0 };
int count = 10;
for (int i = 0; i < count; i++)
{
cout << "Please enter a number for value " << i + 1 << " :";
cin >> input[i];
while (input[i] < 1 || input[i] > 5)
{
cout << "Error: Enter another number between 1 and 5: ";
cin >> input[i];
}
}
cout << endl << "You entered ";
for (int i = 0; i < count; i++)
{
cout << input[i] << " ";
}
cout << "\n";
// show how many times 1 number appears
for (int i = 1; i <= 5; i++)
{
if (input[i] == i)
{
COUNT[i]++;
}
}
for (int i = 0; i < MAX_NO; i++)
{
cout << i + 1 << " appears " << COUNT[i]
<< " times in the input" << endl;
}
cout << endl;
system("pause");
return 0;
}
我刪除了我的消息,純粹是因爲我沒有正確讀取你的信息。因爲這是漫長的一天,非常感謝你在編輯它並解釋它之後,我更好地理解了你的邏輯。是的,我可以看到你是如何做到的。謝謝。 – Collwyr