pseudo random numbers, not random?

Hello pplz..., was just wonderin' if anyone can help me with a problem I am haffing.... I was just tryin' to do a simbple program that asks if you want to fire, and if you do if generates a random number of either 1 or 2. and depending on the generated number, the program will tell the user if missed or not. But heres the problem, I always end up with a hit... why?

Here's my source code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <windows.h>
#include <ctime>
using namespace std;

int main()
{
    char answer;
    int rand_num;
    do{
    cout << "Do you wish to fire?" << endl;
    cin >> answer;
    if (answer == 'y')
    {
               cout << "ok!" << endl;
               cout << "you fired your rifle!" << endl;
               
               srand((int) time(0));            
               int rand_num = (rand() %2) +1 ;
               }
               (rand_num == 1)? cout << "You missed!" << endl : cout << "You hit him!" << endl;      
               }while (answer != exit);  
    
    Sleep(3000);
    cin.get();
    return 0;
    }

what part of this code is incorrect?
can someone help me? thx!
Your program redeclares the variable 'rand_num'.
closed account (z05DSL3A)
srand() should be called once as soon as possible in your code.

As Abramus said, you are declaring another rand_num inside the scope of the if statement, this has the effect of hiding the one in the outer scope (main). When you then do (rand_num == 1) it uses the rand_num from the main scope which has not been changed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
int main()
{
    srand((unsigned int) time(0));
    char answer;
    int rand_num(0);
    do
    {
        cout << "Do you wish to fire?" << endl;
        cin >> answer;
        if (answer == 'y')
        {
            cout << "ok!" << endl;
            cout << "you fired your rifle!" << endl;

                        
            rand_num = (rand() %2) +1 ;
        }
        (rand_num == 1)? cout << "You missed!" << endl : cout << "You hit him!" << endl;      
    }while (answer != exit); //   <--- Don't know how this compiles   

    Sleep(3000);
    cin.get();
    return 0;
}
Ok thnx I think I understand now.
This won't help you any, but it is a valid response to your message title:

http://www.random.org/

:-)
Topic archived. No new replies allowed.