c++arraysrandomsrand

C++ Array of random numbers


I have a bit of a problem with this. I've tried to create a function to return a random number and pass it to the array, but for some reason, all the numbers generated are "0".

#include <iostream>
#include <ctime>
#include <iomanip>
using namespace std;

int generLosNum(int);


int main()
{

    srand(time(NULL));
    int LosNum;
    const int rozmiar = 10;
    int tablica[rozmiar];

    for(int i=0; i<rozmiar; i++)
    {
        tablica[i] = generLosNum(LosNum);
        cout << tablica[i] <<"  ";
    }
return 0;
}
int generLosNum(int LosNum)
{
    int LosowyNum;           
    LosowyNum = (rand() % 10);         
    return (LosNum);
}

Solution

  • So the return for your int generLosNum(int LosNum) was printing 0 because you had it returning LosNum which was initialized equaling to zero. I changed your code so it works and will print out the 10 random numbers.

    #include <iostream>
    #include <ctime>
    #include <iomanip>
    using namespace std;
    
    int generLosNum();
    
    
    int main()
    {
    
        srand(time(NULL));
        int LosNum = 0;
        const int rozmiar = 10;
        int tablica[rozmiar];
    
        for (int i = 0; i < rozmiar; i++)
        {
            tablica[i] = generLosNum();
            cout << tablica[i] << "  ";
        }
        return 0;
    }
    int generLosNum()
    {
        int LosowyNum;
        LosowyNum = (rand() % 10);
        return LosowyNum;
    }