簡體   English   中英

使用cout建立一個表

[英]building a table using cout

我在1到10之間生成20個隨機數。然后我使用switch語句來獲取1到10之間每個可能的隨機數的計數。

我想知道是否存在使用循環顯示一系列變量的替代方法,而不是像下面那樣手動構建表:

        for (int i = 0; i < 20; i++)
    {
        a[i] = generateRandomNumber();

        //record the counts for each possible random number
        switch (a[i]) {
            case 0: ++count_1; break;
            case 1: ++count_2; break;
            case 2: ++count_3; break;
            case 3: ++count_4; break;
            case 4: ++count_5; break;
            case 5: ++count_6; break;
            case 6: ++count_7; break;
            case 7: ++count_8; break;
            case 8: ++count_9; break;
            case 9: ++count_10; break;
        }
    }   

    //output the counts to the screen
    cout << "N  Count\n";
    cout << "1: " << ++count_1 << "\n";
    cout << "2: " << ++count_2 << "\n";
    cout << "3: " << ++count_3 << "\n";
    cout << "4: " << ++count_4 << "\n";
    cout << "5: " << ++count_5 << "\n";
    cout << "6: " << ++count_6 << "\n";
    cout << "7: " << ++count_7 << "\n";
    cout << "8: " << ++count_8 << "\n";
    cout << "9: " << ++count_9 << "\n";
    cout << "10: " << ++count_10 << "\n";

謝謝!

您可以使用數組來計算所有數字出現的頻率 - :

int count[10];
for ( int i = 0; i < 10; i++ )
{
    count[i] = 0;  // Initializing count
}

for ( int i = 0; i < 20; i++ )
{
    a[i] = generateRandomNumber();
    count[a[i]]++;
}

//output the counts to the screen
cout << "N  Count\n";
for ( int i = 0; i < 10; i++ )
{
    cout << i + 1 << " : " << count[i] << "\n";
}

暫無
暫無

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

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