Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New to the CF scene
    Join Date
    Jul 2011
    Posts
    8
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Why is it always zero?

    This is going to be a fairly simple question, but why does this always spit out 0?
    Code:
    #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!";
    }
    
    
    }
    Last edited by HopefulCoder; 11-14-2011 at 02:19 AM.

  • #2
    Supreme Overlord Spookster's Avatar
    Join Date
    May 2002
    Location
    Marion, IA USA
    Posts
    6,273
    Thanks
    4
    Thanked 83 Times in 82 Posts
    Did you run it through a debugger?
    Spookster
    CodingForums Supreme Overlord
    All Hail Spookster

  • #3
    New to the CF scene
    Join Date
    Jul 2011
    Posts
    8
    Thanks
    4
    Thanked 0 Times in 0 Posts
    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.

  • #4
    Rockstar Coder
    Join Date
    Jun 2002
    Location
    USA
    Posts
    9,074
    Thanks
    1
    Thanked 328 Times in 324 Posts
    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.
    OracleGuy

  • Users who have thanked oracleguy for this post:

    HopefulCoder (11-14-2011)


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •