0

So i made this function in a header file and i'm calling it from main.cpp, but it seems like all it does is just count infinitely, even though i put %1000+1. It's in the 10000s now and nothing seems to make it return a number from 1 to 1000.

UsefulFunctions.h :

#ifndef USEFULFUNCTIONS_H
#define USEFULFUNCTIONS_H

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

int generateRandomNr()
{
    srand((unsigned)time(0));
    int x = (rand()%1000)+1;
    return (int)x;
}

#endif // USEFULFUNCTIONS_H

main.cpp :

#include <iostream>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include "UsefulFunctions.h"
using namespace std;

int main()
{
    cout << generateRandomNr();
    return 0;
}

I've tried changing values, just returning rand()%1000+1, rebuilding the project, but nothing worked. It just kept counting and i keep getting results like : 16380 16425 16484 16527

Please help.

  • 2
    You are using `srand` incorrectly. That being said, don’t bother fixing that because you should not be using these functions at all: they’re effectively deprecated in C++. Use the [`` standard header](https://en.cppreference.com/w/cpp/numeric/random), which is (slightly) better. – Konrad Rudolph Apr 16 '20 at 12:24
  • Also, that function should be `inline` or moved out of the header and only the prototype exist. If you were to `#include` that header in multiple modules, the program will fail to link due to a multiple definition error. – PaulMcKenzie Apr 16 '20 at 12:25
  • Thanks much, bout could you give me an example of how to use that properly @KonradRudolph – xDetonator Apr 16 '20 at 12:38
  • Konrad provided links that give examples of using that properly. – Eljay Apr 16 '20 at 12:49

0 Answers0