Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
C++ Code not behaving how i imagined it would?
Ok so i've started to learn C++ and someone gave me the idea to create a dice roll game where you are against an opposing player and you have to roll the highest number. I first wrote out some simple code which allowed a random integer to be generated between the values of 1 and 6. Then i tried to add another player and a winning announcement output code which declares either player 1 or player 2 the winner.
Here is the code:
#include <iostream> // Basic I/O
#include <stdlib.h> // srand, rand
#include <time.h> // time
/*
Aim of the game is too get a higher number than Player 2. The numbers are generated randomly so it is all left to chance
*/
using namespace std;
//Main Function
int main()
{
//Main Player (Player 1)
int p1;
srand (time(NULL));
p1 = rand() % 6 + 1;
cout << "Player 1 has rolled a: " << p1 << endl;
return 0;
//Opponent (Player 2)
int p2;
srand (time(NULL));
p2 = rand() % 6 + 1;
cout << "Player 2 has rolled a: " << p2 << endl;
return 0;
//Winner/Loser Announced
if (p1 > p2)
{cout << "Player 1 has won!" << endl;}
else
{cout << "Player 2 has won!" << endl;}
return 0;
}
Before you say it, i know the announcement section won't work properly because if they get the same number player 2 will win. Just live with it haha i'll sort it out later. Anyway you can clearly see i'm a newbie, so try not to be patronising, however tempted you may be! :D
2 Answers
- MeMeMeLv 77 years ago
Let me guess, the game prints out "Player 1 has rolled a: 4" and then ends.
Two things:
1. First thing is you should really only seed the randomizer once with the current time. A pseudo-RNG will always generate the exact same sequence of random numbers for a given seed. time(NULL) will return the system time in seconds since the epoch, which also means that if both time(NULL) occur within the same second, they will both return the same value. Both rand() calls will probably deliver the same random numbers.
2. The return 0 statement passes control back to the calling function. main() is called from the C/C++ standard library and its return code is passed to exit(). You return right after printing the throw for the first player, so you don't give the statements after any chance to execute.
- 7 years ago
p1 could be less than or equal to p2
give it a try using another if statement rather than else
EDIT: Also try having only one "return 0" at the end, not 3