0

hey does anyone know if i am using the srand() fucntion correctly to randomly choose if a persons letter is X or O?

#include <iostream>
#include <cstdlib>
using namespace std;

int main() {
srand(time(0));
int playerTurn = rand() % 2;
char initPname;
if (playerTurn == 1) 
		{
			initPname= 'X';
			playerTurn++;
                        cout << "Your Letter is X.";
		} else 
		{
			initPname = 'O';
			playerTurn--;
                        cout << "Your letter is O.";
		}
return 0;
}
4
Contributors
7
Replies
8
Views
7 Years
Discussion Span
Last Post by corby
Featured Replies
  • Looks ok to me -- just remember that srand() is executed only once during the entire lifetime of the program while rand() is executed as many times as you need it. Read More

  • 1
    jonsca 1,059   7 Years Ago

    It looks ok. I'm confused as to why you are incrementing and decrementing playerTurn in the branches of the if. Read More

1

Looks ok to me -- just remember that srand() is executed only once during the entire lifetime of the program while rand() is executed as many times as you need it.

1

It looks ok. I'm confused as to why you are incrementing and decrementing playerTurn in the branches of the if.

0

It looks ok. I'm confused as to why you are incrementing and decrementing playerTurn in the branches of the if.

oh i just copied the code from a program im creating(tic tac toe). im just using that to alternate turns. ill put that in a function and call it to do said task.

0

You might have it set up backwards then. Rand() % 2 gives 0 and up to but not including 2. If the value is 1 it gives 'X', which is ok but then it increments giving 2. If the value is 0 it gives 'O', but then it decrements giving -1.

Edited by jonsca: n/a

0

You might have it set up backwards then. Rand() % 2 gives 0 and up to but not including 2. If the value is 1 it gives 'X', which is ok but then it increments giving 2. If the value is 0 it gives 'O', but then it decrements giving -1.

oh ok ill change it then tnx

0

You might have it set up backwards then. Rand() % 2 gives 0 and up to but not including 2. If the value is 1 it gives 'X', which is ok but then it increments giving 2. If the value is 0 it gives 'O', but then it decrements giving -1.

yea i fixed it the decrement and increment where in the wrong brackets. thx for pointing it out

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.