該任務需要三個函數。用戶輸入數字0-9,直到輸入數字10,停止輸入,並對每個數字進行計數,然後輸出每個數字已計數的數量。只有當用戶輸入一個數字時才應該輸出。初學者數組問題,C++
我唯一的問題是,對於用戶不使用的數組中的每個元素,Xcode將其計數爲0,所以最終輸出中有非常大量的零。其他一切正常。
這裏是我的代碼
#include <iostream>
using namespace std;
// counter function prototype
void count(int[], int, int []);
// print function prototype
void print(int []);
int main()
{
// define variables and initialize arrays
const int SIZE=100;
int numbers[SIZE], counter[10], input;
// for loop to set all counter elements to 0
for (int assign = 0; assign < 10; assign++)
{
counter[assign]=0;
}
// for loop to collect data
for (int index=0 ; input != 10 ; index++)
{
cout << "Enter a number 0-9, or 10 to terminate: ";
cin >> input;
// while loop to ensure input is 0-10
while (input < 0 || input > 10)
{
cout << "Invalid, please enter 0-9 or 10 to terminate: ";
cin >> input;
}
// if statements to sort input
if (input >= 0 && input <=9)
{
numbers[index] = input;
}
}
// call count function
count(numbers, SIZE, counter);
// call print function
print(counter);
return 0;
}
// counter function
void count(int numbers[], int SIZE, int counter[])
{
// for loop of counter
for (int index = 0 ; index < 10 ; index++)
{
// for loop of numbers
for (int tracker=0 ; tracker < SIZE ; tracker++)
{
// if statement to count each number
if (index == numbers[tracker])
{
counter[index]++;
}
}
}
return;
}
// print function
void print(int counter[])
{
// for loop to print each element
for (int index=0 ; index < 10 ; index++)
{
// if statement to only print numbers that were entered
if (counter[index] > 0)
{
cout << "You entered " << counter[index] << ", " << index << "(s)" << endl;
}
}
return;
}
@nbro,C++是一個很好的開端語言。 – David
如果你有一位知識淵博的老師,OP顯然沒有。他也可能沒有選擇。 – Puppy
@大衛這是你的意見。 – nbro