Random Number???
Feb 7, 2012 at 9:05pm UTC
Hi. I have used random numbers so many times but I'm confused. It gives me the same number every time. What should I do to fix it. I used the srand(time(0))!!!
My 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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(0));
int playerHP = 100;
int cpuHP = 100;
int playerChoice;
int playerDamage = rand() % 50 + 1;
int cpuChoice = rand() % 3 + 1;
int cpuDamage = rand() % 40 + 1;
string name;
string opponent;
cout << "Enter Name:" << endl;
cin >> name;
cout << endl;
cout << "Enter Opponent:" << endl;
cin >> opponent;
cout << endl;
cout << "Hello and welcome! Today, " << name << " will battle against " << opponent << "." << endl;
cout << endl;
while (playerHP > 0 && cpuHP > 0){
cout << "Choose one of the following moves:" << endl;
cout << "1) Jab" << endl;
cout << "2) Uppercut" << endl;
cout << "3) Hook" << endl;
cin >> playerChoice;
if (playerChoice == 1){
cout << "You chose Jab and dealed " << playerDamage << " damage!" << endl;
cpuHP = cpuHP - playerDamage;
}
else if (playerChoice == 2){
cout << "You chose Uppercut and dealed " << playerDamage << " damage!" << endl;
cpuHP = cpuHP - playerDamage;
}
else if (playerChoice == 3){
cout << "You chose Hook and dealed " << playerDamage << " damage!" << endl;
cpuHP = cpuHP - playerDamage;
}
cout << cpuHP << endl << endl << endl;
}
}
Feb 7, 2012 at 9:12pm UTC
You are generating the random numbers only once. They need to be in the while loop to generate a new one very time.
Btw, it should also be 'dealt' rather than 'dealed'. ;)
Feb 7, 2012 at 9:15pm UTC
ok thx but can u take my code and copy and paste it in to a comment. and just edit the stuff that i need to do?
Feb 7, 2012 at 9:26pm UTC
NVM i got it!
Topic archived. No new replies allowed.