...

View Full Version : Why is it always zero?



HopefulCoder
11-14-2011, 12:09 AM
This is going to be a fairly simple question, but why does this always spit out 0?


#include <iostream>
#include <time.h>
#include <cstdio>
#include <cstdlib>
#include <stdlib.h>

using namespace std;

int roll;

int dice(){
srand(time(NULL));
int roll=rand()%2+1;
return roll;
}

int main(void){
char answer;
cout<<"Flip coin? (y or n) ";
cin>> answer;

if(answer=='y'||answer=='Y'){
dice();
cout<<roll;
}

else{
cout<<"You suck!";
}


}

Spookster
11-14-2011, 02:00 AM
Did you run it through a debugger?

HopefulCoder
11-14-2011, 03:07 AM
Yes, no problems there.

The program runs, but always spits out zero if y or Y is picked.

Which I'm guessing means there is something wrong with the random number generator.

oracleguy
11-14-2011, 04:39 AM
You don't need to seed the RNG every time you call your dice function. You only need to do it once in your main function.

The reason it is always zero though is because you are printing the value of the global variable 'roll' which you are never initializing. (The debugger is just being nice enough to zero it for you.) And you never assign the return value of your dice function to said roll variable. Or you could just cout the result of the function if you wanted.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum