There is clearly something wrong with the else statements in this code.

This program essentially mirrors the attack/defense rules in the game risk. The attacker roles 3 times. The defender 2. The best two roles of the attacker are taken and compared to the defender's two roles.

The defender wins if his role is >= attacker's role, and the attacker wins if his role is > defender's role.

Every execution of the program reports that Dwins wins every time and Awins wins 0 times... I ran the debugger and proved that this is not always the case. In fact, when I go step by step through the program in the debugger, the program runs properly. Only upon execution does it mess up.

Any ideas? Thank you in advance?

#include <cstdlib> 
#include <ctime> 
#include <iostream>

using namespace std;

int Random_Number(){
	srand((unsigned)time(0)); 
	int random_integer = (rand()%6)+1;
    return random_integer;
}
int main (){
	int Defense1, Defense2, Attack1, Attack2, A1, A2, A3 = 0;
	float Dwins, Awins = 0;
	for (int i = 0; i <100; i++){
		Defense1 = Random_Number();
		Defense2 = Random_Number();
		A1 = Random_Number();
		A2 = Random_Number();
		A3 = Random_Number();
		if (A1 >= A2){
			Attack1 = A1;
			Attack2 = A2;
		}
		else{
			Attack1 = A2;
			Attack2 = A1;
		}
		if (A3 >= Attack1){
			Attack2 = Attack1;
			Attack1 = A3;
		}
		if (Attack1 <= Defense1){
			Dwins++;
		}
        else{
			Awins++;
		}
		if (Attack2 <= Defense2){
			Dwins++;
		}
		else{
			Awins++;
		}
	}
	Awins = Awins;
	Dwins = Dwins;
	cout << "Awins" << Awins << "\n\nDwins" << Dwins;
	system("PAUSE");
}

Recommended Answers

All 6 Replies

You didn't set dwin=0???

I got that part.

float Dwins, Awins = 0;

it should be float dwins=0, awins=0

hmm.. I'm still getting the same issue as before. I changed it to float Dwins = 0, Awins = 0;

> srand((unsigned)time(0));
Run at full speed, how much time do you think is going to elapse between the first iteration and the last?
Answer - not much.

In other words, time() returns a constant, therefore your randomiser returns a series of constants, therefore your code always does the same thing.

srand() should be called ONCE ONLY at the beginning of main!

It "works" in the debugger because you slow the whole thing down and time() can change.

ooo. thank you very much

I definitely would not have figured that one out on my own

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.