i've worked for days on this and i can't get it to work

This is a discussion on i've worked for days on this and i can't get it to work within the C++ Programming forums, part of the General Programming Boards category; all right, this is an exercise i was given at school: you have to write a dos program in c++ ...

  1. #1
    Registered User
    Join Date
    Jan 2002
    Posts
    3

    Unhappy i've worked for days on this and i can't get it to work

    all right, this is an exercise i was given at school:
    you have to write a dos program in c++ where you ask the user how many times 1 dice should be thrown.
    the throwing should be done in a function, no problems so far, here's my code all variables are declared properly, so is the function prototype and the headerfiles are ok:

    cout<<"how many times?"<<endl;
    cin>>times;
    for (int i=0; i<=times; i++)
    {result=throwdice();
    cout<<result
    }



    int throwdice()
    {
    int result;
    randomize();
    result=random(6)+1;
    return result;
    }

    you have to calculate the percentage of 1, 2, 3, 4... thrown but that's not the problem.
    the function works but if, for example i let the program throw the dice 3 times i always get the same result; the output of the function is three times the same, it seems that the program refuses to choose the numbers randomly three times, only the first time.
    i hope some of you understand my explanation of the problem and would somebody please help me with this?
    thanks

    stijn

  2. #2
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,789
    You might try calling srand(). It's supposed to work over more compilers than randomise and only needs calling once.

    This is nicely explained in our FAQs, so you would do well to have a look. FAQs

    This should be more what you are looking for;

    Code:
    #include <iostream>
    using namespace std;
    #include <cstdlib>
    #include <ctime>
    
    
    int throwdice(void);
    
    int main(int argc, char *argv[])
    {
    int times;
    srand(time(NULL));
    cout<<"how many times?" <<endl;
    cin>>times; 
    for (int i=0; i<times; i++)
    {
    int result=throwdice();
    cout << "Dice roll " << i+1 << " = " << result << endl;
    } 
     return 0;
     }
    
    
    
    int throwdice(void)
    { 
    int result; 
    
    result=(rand()%6)+1;
    return result; 
    }
    Last edited by Fordy; 01-04-2002 at 09:38 AM.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21