I'm struggling with my "IF" comparison between 3 variables.
The program is supposed to comapare wheels 1, 2 and 3, and reward the player with £5 if all 3 are the same, and £2 if 2 of the 3 are the same.
However sometimes it doesn't work ( gives me £5 even though none are the same)
Please could someone take a look and tell me how to fix it?
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
const char *symbol[4] = {" bell ", " orange ", " cherry ", "horseshoe"};
int main ()
{
srand(time(NULL));
int playagain =1;
int wheel_1,wheel_2,wheel_3;
int i;
int money=10;
int j = (rand()%30)+10;
int start=1;
int k;
printf("you have £%d. Press any key to gamble £1\n", money);
getchar();
while(playagain == 1)
{
for (i=0; i<j; i++)
{
printf("\033[2J\033[0;0f");
printf("\033[%d;%df", 0, 0);
wheel_1 = (rand()%4);
wheel_2 = (rand()%4);
wheel_3 = (rand()%4);
printf("%s ", symbol[wheel_1]);
printf("%s ", symbol[wheel_2]);
printf("%s \n", symbol[wheel_3]);
for (k=0; k<10000000; k++)
{
}
}
printf("%d, %d, %d\n", wheel_1, wheel_2, wheel_3);
if (wheel_1 == wheel_2 == wheel_3)
{
printf("Congrats! You win £5\n");
money = (money+5)-1;
}
else if (wheel_1 == wheel_2 ||
wheel_1 == wheel_3 ||
wheel_2 == wheel_3 )
{
printf("Congrats! You win £2\n");
money = (money+2)-1;
}
else
{
printf("Unlucky, you have lost your £1\n");
money--;
}
printf ("You now have £%d\n", money);
char *replay;
printf ("would you like to play again?");
scanf ("%s", &replay);
if (strcmp(&replay, "yes") == 0)
{
playagain = 1;
}
else
{
playagain = 0;
}
}
}
The way you are using if to compare wheels is wrong
if (wheel_1 == wheel_2 == wheel_3)// Wrong
You should be using
if ((wheel_1 == wheel_2 ) && (wheel_2 == wheel_3))
Almost everything in C returns a value. The expression wheel_2 == wheel_3 also returns a value. The value returned by this expression compares equal to zero if the condition is false else it is non zero(will be 1).
When you do wheel_2 == wheel_3 and suppose the expression is true then it will return 1. This is again compared with wheel_1 like wheel_1 == 1.
As above, it looks like you need:
if((wheel_1 == wheel_2) && (wheel_2 == wheel_3))
Let us know if it works like this :-).
Yes, in here you would have to keep the comparison values differently,
beacuse that x=y=z would return a value and that would be true even though they are not.
Hence you keep them as in associate property if(x==y) && if(y==z) so you naturally get x=z.
Related
I recently wrote a program in C for a calculator. To produce a function that checks if the user input is a prime number or not (amongst other functions).
I essentially used this code (excluding all other functions):
#include <stdio.h>
#include <math.h>
int testForPrime(int);
int main(void) {
int ioperand1 = 0;
printf("\nEnter the value to check if prime (positive integer): ");
scanf("%d", &ioperand1);
if (testForPrime(ioperand1) != 0)
printf("\nThis number is prime.\n");
else
printf("\nThis number is not prime.\n");
return 0;
}
int testForPrime(int operand1) {
int i = 0;
for (i = 2; i <= sqrt(operand1); i++) {
if (operand1 == 0 || operand1 == 1)
return 0;
else if (operand1 % i == 0)
return 0;
else
return 1;
}
}
^
This code above produces the errors
I am not sure why the code produces an error for the value 9 (I fixed that above by adding the condition: if (operand1 == 9), but I don't understand why 9 is seemingly the only value that results in an incorrect solution (It would say 9 was prime, but not any other number give an incorrect result).
One other bug that I remidied with an extra condition statement was the value of 2.
Before adding the extra conditional statement in the main function: if (ioperand1 == 2), the value 2 would always come up as a non prime number.
I originally found this solution to check for prime numbers online, and I still don't understand why the for loop starts from 2.
#include <stdio.h>
#include <math.h>
int testForPrime(int);
int main(void) {
int ioperand1 = 0;
printf("\nEnter the value to check if prime (positive integer): ");
scanf("%d", &ioperand1);
if (testForPrime(ioperand1) != 0 || ioperand1 == 2)
printf("\nThis number is prime.\n");
else
printf("\nThis number is not prime.\n");
return 0;
}
int testForPrime(int operand1) {
int i = 0;
for (i = 2; i <= sqrt(operand1); i++) {
if (operand1 == 0 || operand1 == 1 || operand1 == 9)
return 0;
else if (operand1 % i == 0)
return 0;
else
return 1;
}
}
^This code above fixed the problem, though I don't undesttand why the problem existed in the first place.
TL;DR:
I don't know why this code doesn't work without the extra conditional statements:
if (operand1 == 9) in function definition,
and
if (ioperand1 == 2) in main function.
If anyone could help clear this up, I'd appreciate it.
It is because your prime checking loop does not iterate. It always returns on the first iteration. It must run to completion, and then the number will be prime. So
int testForPrime(int operand1) {
if(operand1 < 2) {
return 0;
}
int sr = (int)round(sqrt(operand1));
for(int i = 2; i <= sr; i++) {
if (operand1 % i == 0) {
return 0;
}
}
return 1;
}
I just started learning programming, so I'm not good enough.
I'd appreciate it if someone could help me:)
Question : Two random values should be made to play a total 10 times of rock-scissors-paper games and produce the following results.
Here is example result.
The 1 th game was won by the computer
(computer = sissors, player = paper)
The 2 th game was won by the player
(computer = paper, player = sissors)
The 3 th game was a draw
(computer = sissors, player = sissors)
......
The 10 th game ~
This is the code I write
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
// 0=rock, 1=paper, 2=sissors
// c = computer , p = player
srand(time(NULL));
for(int i=0; i<10; i++)
{
int c;
int p;
c = rand() % 3;
p = rand() % 3;
sprintf (rock, "%d", 0);
sprintf (paper, "%d", 1);
sprintf (sissors, "%d", 2);
if (c == p)
{
printf("The %d th game was a draw \n", i+1);
printf(" (computer = %s, player = %s)",c,p);
}
else if ((c == 0 && p == 2) || (c == 1 && p == 0) || (c == 2) && (p == 1));
{
printf("The %d th game was won by the computer. \n", i+1);
printf(" (computer = %s, player = %s\n)",c,p);
}
else
{
printf("The %d th game was won by the player \n", i+1);
printf(" (computer = %s, player = %s\n)",c,p);
}
}
return 0;
}
You can try something like this, and I think its an elegant solution. By defining the outcome table, you can get the text accordingly.
static const int outcome[3][3] =
{
{ 0, 2, 1 },
{ 1, 0, 2 },
{ 2, 1, 0 }
};
static const char * signs[3] =
{
"rock",
"paper",
"scissors"
};
static const char * texts[3] =
{
"was a draw",
"was won by the player",
"was won by the computer"
};
int main()
{
//<..>
printf("The %i th game %s (computer = %s, player = %s)\n", i+1, texts[outcome[p][c]], signs[c], signs[p]);
//<..>
}
You could've just stored the three possible outcomes as a single 2D character array or as a const char * mentioned by #dratenik in the comments. I used a 2D array just to make the approach simple:
char r[3][7]={"Rock","Paper","Scissor"};
As for the for loop, I'd change your last else if statement to something like this:
else if((c==0 && p==2)||(c==1 && p==0)||(c==2 && p==1))
instead of what you did:
else if ((c == 0 && p == 2) || (c == 1 && p == 0) || (c == 2) && (p == 1));
Note that, here, we're dealing with cases like A or B or C or.... where each event A comprises of further cases a and b and c and.... In your case, what you did meant something like A or B or C and D. Learn how to use the brackets in C and also about Semicolons in C.
Finally, the printf statement of the above else if part (did not abide by your specified format, but you can edit that):
printf("Computer: %s\nPlayer: %s\nComputer wins\n",r[c],r[p]);
The code is as follows:
guessing game , 10 guesses max, prompts user for replay. It crashes after one run. It works fine without the replay() module but then I can't incorporate the replay option. I have tried several different things to no avail. Please kindly help me resolve this in a timely manner. Help is appreciated in advance.
thanks
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void guessGame ();
int replay();
int main()
{
int selection;
printf("Welcome to the Number Guess Game! I choose a number between 1 and 100 and you\nhave only 10 chances to guess it!");
do
{
printf("\n\nok, I made my mind!");
guessGame();
replay();
}
while (replay() != 0);
printf("Thank you! have a nice day.\n");
return 0;
}
void guessGame()
{
int attempt,guess;
srand(time(NULL));
int r = rand () % 100 + 1;
for (guess = 1; (guess < 11 && attempt != r); guess = guess + 1)
{
printf("\nWhat is your guess> ");
scanf("%d",&attempt);
if (attempt < 1 || attempt > 100)
{
printf("Invalid guess!\n");
guess = guess - 1;
}
else
{
if (attempt > r && guess < 10)
printf("My number is smaller than %d\n",attempt);
else if (attempt < r && guess < 10)
printf("My number is larger than %d\n",attempt);
}
if ((guess < 9) && (attempt >= 1 && attempt <= 100))
printf("%d guesses left.\n",(10 - guess));
if ((guess == 9) &&(attempt >= 1 && attempt <= 100))
printf("%d guess left.\n",(10 - guess));
}
if (attempt == r)
{
printf("You did it! My number is %d.\nYou did it in %d guesses.\n",r,guess);
}
if (guess >= 10 && attempt != r)
{
printf("SORRY! you couldn't guess it with 10 guesses.\nMy number was %d. Maybe next time!\n",r);
}
}
int replay()
{
char selection;
printf("\nDo you want to play again");
scanf("%c",selection);
if (selection == 'N')
return 0;
else
return 1;
}
You're calling scanf() incorrectly. You need to give the address of the variables to store into:
scanf("%c", &selection);
this is both my first time asking a question and also one of my first times writting such a big programm. As you might guess im new at programming.
Alright the source code:
#include <stdio.h>
typedef struct{
int **a;
int size;
}_board;
typedef _board* board;
typedef struct{
int row,col;
}position;
int main () {
int i, j, turn=1, victory = 0, num=0;
_board b;
char P1symbol, P2symbol, mark, boardarray[b.size][b.size];
position p;
printf("WELCOME TO THE GAME OF TIC TAC TOE!\n");
do {
printf("\nwill player one, use X or O as his symbols? select by pressing x or o\n");
scanf(" %c", &P1symbol);
if (P1symbol == 'x' || P1symbol == 'o') {
num = 1;
}
} while ( num == 0);
if (P1symbol == 'x') {
P2symbol = "o";
}
else {
P2symbol = "x";
}
do {
printf("\n now choose the size of the game board, type a numeral and press enter");
scanf("%d", &b.size);
}while (b.size <= 0);
for (i=0; i=b.size; i++){
for (j=0; j=b.size; j++){
boardarray[i][j] = "-";
}
}
do {
do {
boardsketch(boardarray, b.size);
if (turn%2 == 1) {
printf("player 1, please choose a box to input you mark on");
mark = P1symbol;
}else{
printf("player 2, please choose a box to input you mark on");
mark = P2symbol;
}
printf("type the coordinates i,j, which correspond to the row and collumn number");
printf("make sure the numbers are valid, not taken, and between 0 and %d", b.size);
scanf("%d %d", &p.row, &p.col);
}while (p.row > b.size && p.row < 0 && p.col > b.size && p.col <0 && boardarray[p.row][p.row] != "-");
turn++;
boardarray[p.row][p.col] = mark;
} while (wincheck(boardarray, p.row, p.col, b.size) != 1);
return 0;
}
int wincheck(int row, int col, int size, char boardarray[size][size])
{
if (boardarray[row][col] = boardarray[row -1][col -1] = boardarray[row +1][col +1]) {
return 1;
}
if (boardarray[row][col] = boardarray[row -1][col] = boardarray[row +1][col]) {
return 1;
}
if (boardarray[row][col] = boardarray[row][col -1] = boardarray[row][col +1]){
return 1;
}
if (boardarray[row][col] = boardarray[row -1][col +1] = boardarray[row +1][col -1]){
return 1;
}
}
void boardsketch(int size, char boardarray[size][size]) {
int i, j;
for (i=0; i=size; i++) {
for (j=0; j=size; j++) {
if (boardarray[i][j] == '-') {
printf("| ");
} else {
printf("%c |", &boardarray[i][j]);
}
}
}
}
Now the program's purpose is to simulate a game of tic tac toe (with the addition of the user, deciding the size of the game board). My problem is that, altough compilation IS achieved the program does 2 wierd behaviors when reaching a specific line, that line being:
do {
printf("\n now choose the size of the game board, type a numeral and press enter");
scanf("%d", &b.size);
}while (b.size <= 0);
If i input a value that doesnt obey to b.size <= 0, the printf above, repeats indefinately, if i DO put a correct value, the programm doesnt resume. What am i doing wrong? again im new at programming sooooo... go easy on me :D
There are compiler errors in your code. I don't know how you got it to compile and build it the first place.
Compiler errors:
You have:
P2symbol = "o";
Type of "o" is char const*. The type of P2symbol is char. What you need is
P2symbol = `o`;
Few lines after that, you have:
P2symbol = "x";
That needs to be changed to:
P2symbol = `x`;
Few lines after that, you have:
boardarray[i][j] = "-";
It suffers from the same compiler error. You need to change it to:
boardarray[i][j] = `-`;
Your declaration and definition of boardsketch does not match with the way you are calling it. Your call is:
boardsketch(boardarray, b.size);
You have defined it as:
void boardsketch(int size, char boardarray[size][size]) {
....
}
You need to change either the call or the function definition so that they match. Also, you should declare the function before it is used. Add
void boardsketch(int size, char boardarray[size][size]);
before the start of main.
The definition and call of wincheck suffers from the same error. It also should have a declaration before it's usage.
A few lines after that call to boardarray, you have the line:
}while (p.row > b.size && p.row < 0 && p.col > b.size && p.col <0 && boardarray[p.row][p.row] != "-");
The last part of that statement suffers from the char and char const* mismatch. You need to change it to:
}while (p.row > b.size && p.row < 0 && p.col > b.size && p.col <0 && boardarray[p.row][p.row] != '-');
Run Time Errors:
You have:
_board b;
char P1symbol, P2symbol, mark, boardarray[b.size][b.size];
The problem with that is b.size is not initialized. It could be anything. Using it to declare broadarray is problem. Imagine the chaos that will ensue if the b.size were to be initialized to a negative number. For sane and predictable behavior, you should initialize b properly before using its data.
A few lines below, you are asking for size to be input by the user.
do {
printf("\n now choose the size of the game board, type a numeral and press enter");
scanf("%d", &b.size);
}while (b.size <= 0);
There is a logic error here. You are asking for the size of the board after you have already created boardarray. What you could do is gather the initial input and use them to call another function where the core of the game play happens.
/* Function that contains the core part of playing the game */
void playgame(char P1symbol, char P2symbol, int size)
{
int i, j, turn=1, victory = 0;
char mark, boardarray[size][size];
position p;
for (i=0; i=size; i++){
for (j=0; j=size; j++){
boardarray[i][j] = '-';
}
}
do {
do {
boardsketch(size, boardarray);
if (turn%2 == 1) {
printf("player 1, please choose a box to input you mark on");
mark = P1symbol;
}else{
printf("player 2, please choose a box to input you mark on");
mark = P2symbol;
}
printf("type the coordinates i,j, which correspond to the row and collumn number");
printf("make sure the numbers are valid, not taken, and between 0 and %d", size);
scanf("%d %d", &p.row, &p.col);
}while (p.row > size && p.row < 0 && p.col > size && p.col <0 && boardarray[p.row][p.row] != '-');
turn++;
boardarray[p.row][p.col] = mark;
} while (wincheck(p.row, p.col, size, boardarray) != 1);
}
Now, main can be simplified to:
int main () {
char P1symbol;
char P2symbol;
int size;
int num = 0;
printf("WELCOME TO THE GAME OF TIC TAC TOE!\n");
do {
printf("\nwill player one, use X or O as his symbols? select by pressing x or o\n");
scanf(" %c", &P1symbol);
if (P1symbol == 'x' || P1symbol == 'o') {
num = 1;
}
} while ( num == 0);
if (P1symbol == 'x') {
P2symbol = 'o';
}
else {
P2symbol = 'x';
}
do {
printf("\n now choose the size of the game board, type a numeral and press enter");
scanf("%d", &size);
}while (size <= 0);
playgame(P1symbol, P2symbol, size);
return 0;
}
Ah, the problem is your for loop after the do while. You are assigning your counters instead of evaluating the limits. Asigning them will result to true every time. Try this instead:
for (i=0; i<b.size; i++){
for (j=0; j<b.size; j++){
boardarray[i][j] = "-";
}
}
Also, do not create an array with undefine value b.size...
wiHi everyone since last time i found extreme help on here, im gonna ask a question again
My code doesnt return right values :
something is wrong in the play_game function and i cant figure out what it is.I believe that all cases are covered but somehow they end up messed up.
also the code doesnt loop for everytime i want to play a game after the second game it stops.
this is not an assignment
any suggestion?
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
static int sum, point, win = 0, roll = 0;
bool play_game(void);
int roll_dice(void);
int main(void){
srand(time(NULL));
play_game();
char input[10];
do{ point = 0;
play_game();
if(win == 1){ // I'm assuming that play returns whether you won or not
printf("You won!\n");
}else{
printf("You lost!\n");
}
printf("Would you like to continue? y/n\n");
gets(input);
}while(*input == 'y'); // gets() flushes the buffer for next time you need input
return 0;
}
bool play_game(void){
point=0;
roll_dice();
printf("Your point is %d\n", sum);
while(roll == 1) /* first round */
{
if(sum == 7 || sum == 11)
return win = 1;
else if(sum == 2 || sum == 3 || sum == 12)
return win = 0;
else if(sum == 1 || sum == 4 || sum == 5 || sum == 6 || sum == 8 || sum == 9 || sum == 10){
point=sum;
roll_dice();
}
}
while(roll > 1) /* all others rounds*/
{
if(sum == 7)
return win = 0;
else if(sum == point)
return win = 1;
else if(sum != point || sum != 7)
roll_dice();
}
}
int roll_dice(void){
int a,b;
a=1+rand() % (6);
b=1+rand() % (6);
sum=a+b;
roll++;
printf("You rolled %d\n", sum);
return sum;
}
OUTPUT
A couple of points:
You probably want 1 + rand() % 6
The return value of printf() is probably not what you want to return from roll_dice()
The loop needs to be more like:
main(){
char input[10];
do{
score = 0; //Always initialize the score
if(play_game()){ // I'm assuming that play returns whether you won or not
printf("You won!\n");
}else{
printf("You lost!\n");
}
printf("Would you like to continue? y/n\n");
gets_s(input, 9);
}while(*input == 'y'); // gets() flushes the buffer for next time you need input
}
Kyle's answer is just fine (as I see it), But I can spot a few problems, hope it'll help you in further cases.
You always win, and I know it's nice, but I bet it's not the expected behavior:
while(true) // This will always happen, because true is always evaluated as true
{
printf("Won\n\n");
printf("Play again? y/n: ");
break;
}
while(false) //This will never happen, since false is always evaluated as false
{
printf("Lost\n\n");
printf("Play again? y/n: ");
break;
}
I think you meant to check the result of play_game(). So add another variable and check against it:
bool win;
win = play_game();
while (win == true)
...
while (win == false)
...
Why using while loop there? you break it in the first iteration anyway
if(win == true)
{
printf("Won\n\n");
}
else
{
printf("Lost\n\n");
}
printf("Play again? y/n: ");
The game will run not more than twice, because you don't have a loop that depends on the answer, but only an if statement that is evaluated just one time:
if(v=getchar() == 'y') //This is the second time the code runs, after that? nada.
{
point =0; /* reset point var */
play_game();
}
else if(v=getchar() == 'n') // Why adding this check? you're going out anyway after the if-else
exit(1);
EDIT
When you use a while loop, what you do is saying:
While (some expression in the parenthesis) is true, execute the code in the block {..} and then check again the expression in parenthesis.
If you write while(true), you actually writing while true is true, execute the code in the block. And this will always happen.
If you write while(false) you actually write while false is true, execute the code in the block. and this false is never true, than it will never execute the code in the block.
If you want a real condition here, you can use while(play_game()). this is like writing, while the returned value from the function play_game is true, execute the code in the block and then the code will be executed only when the play_game function return true (which indicates a win in the game).
There are many good C tutorials out there, start here or here
It is hard to tell from your description (please say what you expected to happen, and what happened instead), but the first thing I notice is that you are rolling 5-sided dice for a and b.
Rolling of the dice is happening at at incorrect points during your game sequence.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
// add defines to make states easier to read
#define WIN 1
#define LOSE 0
static int sum, point, win = 0, roll = 0;
//bool play_game(void);
int play_game(void); // changed return type to be int
int roll_dice(void);
int main(void){
srand(time(NULL));
// play_game(); // unncessary
char input[10];
do
{
point = 0;
//play_game();
// if(win == 1){
if(play_game()){ // use return value from play_game()
printf("You won!\n");
}else{
printf("You lost!\n");
}
printf("Would you like to continue? y/n\n");
// gets(input);
fgets(input, sizeof(input), stdin); // a safer input read
} while(*input == 'y'); // gets() flushes the buffer for next time you need input
return 0;
}
// bool play_game(void)
int play_game(void) // changed return type to be int
{
point=0;
// remove as this messes up the roll sequence.
// roll_dice();
// incorrect place to display this message
//printf("Your point is %d\n", sum);
// the while loop here is unnecessary
//while(roll == 1) /* first round */
//{
roll_dice(); // add for initial come out roll.
if(sum == 7 || sum == 11) { // I use braces to remove ambiguity
// return win = 1;
return WIN;
} else if(sum == 2 || sum == 3 || sum == 12) {
//return win = 0;
return LOSE;
}
// sum will never be 1
// on that note if it control reaches here it will be one of the other numbers.
//} else if(sum == 1 || sum == 4 || sum == 5 || sum == 6 || sum == 8 || sum == 9 || sum == 10){
// point=sum;
// roll_dice(); // remove as this messes up the roll sequence.
// }
point=sum;
printf("Your point is %d\n", sum);
//}
// while(roll > 1) /* all others rounds*/
while (1) // might as well loop forever
{
roll_dice(); // add for subsequent dice rolls
if(sum == 7) {
//return win = 0;
return LOSE;
} else if(sum == point) {
// return win = 1;
return WIN;
}
// remove as this is unnecessary
// else if(sum != point || sum != 7)
// remove as this messes up the roll sequence.
//roll_dice();
}
}
int roll_dice(void){
int a,b;
a=1+rand() % (6);
b=1+rand() % (6);
sum=a+b;
// roll++; // unncessary
printf("You rolled %d\n", sum);
return sum;
}