Search code examples
c++classrandom-seedseedsrand

Why does this code always generate zero when I want to generate random numbers? How can I fix the problem?


#include <iostream>
#include<stdio.h> 
#include<stdlib.h> 
#include<time.h> 
 
using namespace std;
 
class mRND
{
    public:
        void seed()
        {
            srand(time(0)); 
            _seed = rand();
        }
 
    protected:
        mRND() : _seed(), _a(), _c(), _m(2147483648)
        {
        }
        int rnd()
        {
            return (_seed = (_a * _seed + _c) % _m);
        }
 
        int _a, _c;
        unsigned int _m, _seed;
};

int main() {
    mRND r;
    for(int i=0;i<100;i++)
    cout<< r.rnd()<<endl;
    
    return 0;  
}

Solution

  • Your problem is here:

    return (_seed = (_a * _seed + _c) % _m);
    

    _a is 0 so the returned value is 0 and it never changes (since _a is always 0).