I'm currently working on my assignment, but I can't get it to continue when user hit's 'r' or 'R'. Do I have to add a do while loop or is there another easier way to do it without loops?
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
int roll();
int main ()
{
int x, y, z, num;
int score = 0, rollscore;
char roll;
time_t t;
printf("Human player rolls First, Press 'R' to roll the Die.\n");
scanf("%c", &roll);
srand((unsigned)time(&t));
while (roll== 'r' || roll == 'R')
{
for (x=0; x<1; x++)
{
x = rand() % 6 +1;
printf("%d\n", x);
rollscore+=x;
printf("Your score is now %d\n", rollscore);
printf("Roll Again? Press R to roll or H to hold\n");
scanf("%c", &roll);
}
while(roll == 'r' || roll == 'R');
if(roll == 'h' || roll == 'H')
printf("You chose to hold. Your score is %d", rollscore);
//break;
}
// rollscore=x;
//score = x;
// if (x==1)
// {
// printf("1 was rolled. Your turn is over.\n");
//}
return 0;
}
a while loop is a reasonable way to program it. However repeating line 20 at line 31 appears to indicate that you need to clear up the logic a bit. A simple flowchart outlining the framework will help you use a single while loop at line 20.
printf("Human player rolls First, Press 'R' to roll the Die.\n");
scanf("%c", &roll);
srand((unsigned)time(&t));
while (roll== 'r' || roll == 'R')
{
for (x=0; x<1; x++)
{
x = rand() % 6 +1;
printf("%d\n", x);
rollscore+=x;
printf("Your score is now %d\n", rollscore);
printf("Roll Again? Press R to roll or H to hold\n");
//scanf("%c", &roll);
}
//break;
}
When I cancel out the scanf statement, it just keeps running my program infinitely, how do I get it to where it can read my scanf value?
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
int roll();
int main ()
{
int x, y, z, num;
int score = 0, rollscore;
char roll = '0';
time_t t;
printf("Human player rolls First, Press any button to roll the die.\n");
//scanf("%c", &roll);
srand((unsigned)time(&t));
do
//while (roll== 'r' || roll == 'R')
{
//for (x=0; x<1; x++)
x = rand() % 6 +1;
if (x==1)
{
printf("1 was rolled. Your turn is over.\n");
break;
}
printf("%d\n", x);
rollscore+=x;
printf("Your score is now %d\n", rollscore);
printf("Roll Again? Press R to roll or H to hold\n");
scanf("%c", &roll);
x++;
}
while(roll == 'r' || roll == 'R');
getchar();
if(roll == 'h' || roll == 'H')
printf("You chose to hold. Your score is %d", rollscore);
return 0;
}
There seem to be three separate cases involving H, R and x = 1. Each determines if the player and the computer get to have a turn or continue to have turns. A flowchart is a good way to get the logic nailed before you write code.