-
Stuck! (easy problem)
Why doesnt this work?
Its giving me a headick!
Code:
#include <conio.h>
#include <cstdlib>
#include <iostream>
#include <stdio.h>
#include <time.h>
using namespace std;
double random_number;
double number_generator()
{
srand( time(NULL) );
random_number = rand()%10+1;
return random_number;
}
int main()
{
cout << random_number;
getch();
return 0;
}
-
random_number is never defined in main();
before outputing it do: random_number = number_generator();
and seed rand in main as well.
edit:: follow one of the other suggestions as well and don't use global variables.
-
>>Its giving me a headick!
*giggle*
Ok. Do srand() at the top of main(), not in number_generator(). Next, you aren't ever calling number_generator(). That would be why random_number isn't getting a random number. Then, your 'random number' generator is trying to operate on a double, when rand() only deals with ints. And you shouldn't be using the global variable.
Code:
#include <iostream>
#include <ctime>
#include <conio.h>
using namespace std;
int number_generator()
{
return rand()%10+1;
}
int main()
{
srand(time(NULL));
cout << number_generator();
getch();
return 0;
}
-
It's because your not actully calling the function try something like this
Code:
double number_generator()
{
double random_number = rand()%10+1;//This does not need to be a global
return random_number;
}
int main(void)
{
srand(time(NULL));
cout<<number_generator();//this will print out what number_generator returns
return 0;
}
-
Thanks all. I'm new to c++ so it's really nice to have you guys here :).