2014-12-20 120 views
1

該任務需要三個函數。用戶輸入數字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; 
} 
+4

@nbro,C++是一個很好的開端語言。 – David

+0

如果你有一位知識淵博的老師,OP顯然沒有。他也可能沒有選擇。 – Puppy

+0

@大衛這是你的意見。 – nbro

回答

2

什麼你指的是作爲「的XCode計數[和]爲0」,其實只是初始化值。鑑於您已決定將用戶的輸入限制爲0-9,解決此難題的簡單方法是在您調整數組大小後立即遍歷數組並將每個值設置爲-1。

之後,當用戶完成他們的意見,而不是僅僅cout荷蘭國際集團的每一個值,只能用一個有條件的打印類似如下:

if (counter[index] != -1) 
{ 
    cout << "You entered " << counter[index] << ", " << index << "(s)" << endl; 
} 

注意,這是什麼樣的使用情況下,這是多大更適合於鏈接列表或向量之類的東西。就目前而言,你並沒有做任何事情來調整數組大小,或防止溢出,所以如果用戶試圖輸入超過100個數字,你會遇到嚴重的問題。

1

首先,這不是對您確切問題的回答,而是關於如何以更簡單的形式編寫代碼的建議。

我不會爲你寫這個,因爲它是一個任務,而且是一個相當簡單的。就編碼而言,看起來你對事物有很好的把握。

考慮一下:

您需要允許用戶輸入0-10,清點0-9的。一個數組包含索引,並且一個整數數組10,可以容納這些索引計算的10個數字。現在你只需要坐着一些空的int,爲什麼不用它們來計數呢?

代碼提示:

++numbers[input]; 

二提示:不要忘了一切初始化爲零。

+0

我可以有其他提示嗎?這是我有史以來第一個計算機科學課程,所以我的編程肌肉仍然不強(足以使用該提示)。 – republikunt

+0

絕對。首先幫助我瞭解你在哪裏/你在哪裏迷路的提示。 – David