簡體   English   中英

C++ 檢查結果數組中有多少次數字

[英]C++ Check how many times there are numbers in the resulting array

我是 C++ 的初學者,有人可以幫助我。 INT 數組。隨機。 用 10 到 77 的隨機數填充 1000 個整數的數組。檢查結果數組中有多少次有數字 10、20、30、40、50、60、70。打印接收到的統計信息。

我看到它是這樣的,但我不知道如何計算數組中的數字。

int main()
{
    int number[1000];
    int countUnits[7];
    int count = 0;
    srand(time(NULL));
    for (int i = 0; i < 1000; i++) {
        number[i] = rand() % 68 + 10;

    }
    for (int i = 0; i < 1000; i++) {
        if (number[i] % 10 == 0) {

        }
    }
}

就像只數一個數字一樣開始,除了你有七張支票和七個計數器:

for (int i = 0; i < 1000; i++)
{
    if (number[i] == 10)
        countUnits[0] += 1;
    else if (number[i] == 20)
        countUnits[1] += 1;
    else if ...
...
}

然后您注意到測試和索引有一個模式,並簡化:

for (int i = 0; i < 1000; i++)
{
    if (number[i] % 10 == 0)
        countUnits[number[i]/10-1] += 1;
}

或者,如果您想讓人們對您的 m4d sk1llz 感到困惑:

for (int i = 0; i < 1000; i++)
{
    countUnits[number[i]/10-1] += number[i] % 10 == 0;
}

你不遠了。 但是您應該首先初始化countUnits

int countUnits[7] = {0};    // enough to zero initialize the whole array

然后你可以數:

for (int i = 0; i < 1000; i++) {
    if (number[i] % 10 == 0) {
        countUnits[number[i] / 10 - 1] += 1;
    }
}

這樣,您只需掃描一次陣列。

countUnits的索引必須基於number[i]的值。

不是i像其他人建議的那樣。 有了這個(例如)如果索引i是 934 並且可以被 10 整除,那么結果索引將是 92

這是代碼(請原諒printf ):

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int
main(void)
{
    int number[1000];
    int countUnits[7] = { 0 };

    srand(time(NULL));

    for (int i = 0; i < 1000; i++) {
        number[i] = rand() % 68 + 10;
    }

    for (int i = 0; i < 1000; i++) {
        int value = number[i];
        if (value % 10 == 0)
            countUnits[value / 10 - 1] += 1;
    }

    for (int i = 0; i < 7; i++)
        printf("%d: %d\n",(i + 1) * 10,countUnits[i]);

    return 0;
}

由於這是 C++,它應該更容易。 它讀起來更像 Python 而不是 C。 在這種情況下,這是一件好事!

我是這樣寫的:

#include <array>
#include <iostream>
#include <map>
#include <random>

int main()
{
    std::random_device rd;  //Will be used to obtain a seed for the random number engine
    std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
    std::uniform_int_distribution<> distrib(10, 77);

    std::array<int, 1000> numbers;
    for (auto &number : numbers)
        number = distrib(gen);

    std::map<int, int> counts;
    for (auto const &number : numbers)
        if ((number % 10) == 0)
            counts[number] ++;

    for (auto const &number_count : counts)
    {
        auto number = number_count.first;
        auto count = number_count.second;
        std::cout << number << " found " << count
            << (count == 1 ? " time" : " times") << '\n';
    }
}

樣品 output:

10 found 13 times
20 found 15 times
30 found 13 times
40 found 7 times
50 found 15 times
60 found 9 times
70 found 17 times

暫無
暫無

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

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