Reputation: 39
So I am creating a random number generator and I keep getting a problem. In my program I have it print out the code into the "int main()" function. The problem is that it prints a 0 after. It's also saying I have to use return, but I don't want to. I want to keep the random number generator in another function because I will be adding much more in the future.
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int randRoll();
//Calls the other function
int main()
{
cout << randRoll() << endl;
system("Pause");
}
//Gets the random number
int randRoll()
{
srand(time(0));
for (int x = 1; x <= 1; x ++)
{
cout <<"Your random number is " << 1 +(rand()%4) << endl;
}
return 0;
}
Upvotes: 2
Views: 82
Reputation: 300419
Well, of course it prints two numbers, you asked it to!
// This prints "Your random number is [1-4]\n"
cout <<"Your random number is " << 1 +(rand()%4) << endl;
// This prints "0\n" since "randRoll()" returns 0
cout << randRoll() << endl;
Your main function could just be int main() { randRoll(); }
because randRoll
already prints something.
Upvotes: 0
Reputation: 145457
#include<iostream>
#include<stdlib.h>
#include<time.h>
using namespace std;
//Gets the random number
int randRoll()
{
return 1 +(rand()%4);
}
//Calls the other function
int main()
{
srand( static_cast<unsigned>( time(0) ) );
for (int x = 1; x <= 7; x ++)
{
cout <<"Your random number is " << randRoll() << endl;
}
}
Salient points:
<stdlib.h>
, not <cstdlib>
, to avoid some problems.srand
only once.Upvotes: 1
Reputation: 24648
Try this instead:
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int randRoll();
// entry point
int main()
{
srand(time(0)); // initialize randomizer
cout << randRoll() << endl;
system("Pause");
return 0;
}
//Gets the random number
int randRoll()
{
auto x = 1 +(rand()%4);
// do something with x here (but don't call cout!)
return static_cast<int>(x);
}
The problem you have is that you are not returning the randomly generated value (which I called x
in my code). Also, you were trying to print out the randomly generated value twice (but incorrectly).
Upvotes: 1
Reputation: 62906
cout << randRoll() << endl;
That prints out return value of that function, which is 0. How could not, when you tell it to print it? Well, like this, by not asking it to print return value:
randRoll(); // prints some random numbers
cout << endl; // prints newline
Then return value is ignored, and you can change it to void
type if you want.
Note that as a whole, doing it like this might not make sense, but I think that answers your question and allows you to move on to next problem...
Upvotes: 0