dimanche 17 octobre 2021

Attempting to divide using an int in an array, junk numbers come out when attempted C++

When I try and get the frequency of each number occurring in the array filled with random numbers. When attempting to get an output all of the numbers come out as junk.

#include <iostream>

using namespace std;

int main()
{
    int highestNumber, outputLength, result;
    cout << "What's the highest number you want to generate?: ";
    cin >> highestNumber;
    cout << "How long of a number sequence do you want to generate?: ";
    cin >> outputLength;
    cout << "Okay we will generate " << outputLength<< " number(s) ranging from 1 to " << highestNumber << "!\n";
    srand(time(NULL));
    int * randomNumbers = new int[outputLength];
    for (int i = 1; i <= outputLength; i++) {
        result = rand() % highestNumber+ 1;
        cout << result << ", ";
        randomNumbers[i] = result;
    }
    
    int * numberCounter = new int[highestNumber];
    cout << "\nFrequency:\n";
    for (int i = 1; i <= highestNumber; i++) {
        int temp2 = randomNumbers[i];
        numberCounter [temp2 - 1] = numberCounter [temp2 - 1] + 1;
    }
    for (int i = 1; i <= highestNumber; i++) {
        int frequency = 0;
        frequency = numberCounter [i] / outputLength;
        cout << numberCounter [i] << " occurs " << frequency << " of the time\n";
    }
}

Output:

What's the highest number you want to generate?: 5
How long of a number sequence do you want to generate?: 10
Okay we will generate 10 number(s) ranging from 1 to 5!
5, 3, 3, 1, 1, 5, 4, 3, 1, 3,
Frequency:
-842150451 occurs -84215045 of the time
-842150449 occurs -84215044 of the time
-842150451 occurs -84215045 of the time
-842150450 occurs -84215045 of the time
-33686019 occurs -3368601 of the time



Aucun commentaire:

Enregistrer un commentaire