I'm trying to make a craps game where there would be dice rolling to check if it hits the target. I can't be sure what's wrong with my while loop but it keeps running even when the while loop requirement is false. Here is my code:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int rollDice() {
int sum, d1, d2;
sum = 0;
d1 = (rand() % 6) + 1;
d2 = (rand() % 6) + 1;
sum = d1 + d2;
printf("Player rolled %d + %d = %d\n", d1, d2, sum);
return sum;
}
int main() {
int player, target, tries;
srand(time(NULL));
tries = 0;
player = rollDice();
target = player;
if (player == 7 || player == 11) {
printf("Player wins.\n");
}
else if (player == 2 || player == 3 || player == 12) {
printf("Player loses.\n");
} else {
printf("Point is %d. The game continues: \n", target);
player = rollDice();
}
printf("Player is %d, Target is %d.\n", player, target);
while (target != player || player != 7) {
player = rollDice();
}
return 0;
}
The game ends when a 7 is thrown or when the player's score is thrown again. Hence the while test should be while (target != player && player != 7), not while (target != player || player != 7).
You must also move the while loop inside the last else block.
Here is a modified version:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int rollDice(void) {
int sum, d1, d2;
sum = 0;
d1 = rand() % 6 + 1;
d2 = rand() % 6 + 1;
sum = d1 + d2;
printf("Player rolled %d + %d = %d\n", d1, d2, sum);
return sum;
}
int main() {
int player, target, tries;
srand(time(NULL));
tries = 0;
player = rollDice();
target = player;
if (player == 7 || player == 11) {
printf("Player wins.\n");
} else
if (player == 2 || player == 3 || player == 12) {
printf("Player loses.\n");
} else {
printf("Point is %d. The game continues:\n", target);
player = rollDice();
printf("Player is %d, Target is %d.\n", player, target);
for (;;) {
if (player == 7) {
printf("Pass loses\n");
break;
}
if (player == target) {
printf("Pass wins\n");
break;
}
player = rollDice();
}
}
return 0;
}
Related
I have this super simple code for calculating averages of given even and odd numbers, until the user gives 0. (I would use for loop but we can't).
I'm having a really strange problem with program rounding results like 25/2 is 2.00000. Sorry if this question is stupid but I just can't find a problem.
What am I doing completely wrong?
#include <stdio.h>
#include <stdlib.h>
void funkcja()
{
int sumaNiep = 0;
int sumaPa = 0;
int userInput = 1;
int i = 0;
while(userInput != 0)
{
//wprow zmiennej
printf("%d. Podaj calkowita liczbe: ", i+1);
scanf("%d", &userInput);
//jesli parzysta
if (userInput % 2 == 0)
{
sumaPa += userInput;
} else {
sumaNiep += userInput;
}
i++;
}
double sredniaNiep = sumaNiep/(i-1);
double sredniaPa = sumaPa/(i-1);
printf("\nsrednia parzysta %d / %d : %lf", sumaPa, i, sredniaPa);
printf("\nsrednia parzysta %d / %d : %lf", sumaNiep, i, sredniaNiep);
}
int main()
{
funkcja();
}
The problem is that you do an integer division at the end.
You should break out of the loop if the user enters 0 and make at least one operand a double when you do the division. You also need to count the number of evens and odds:
#include <stdio.h>
#include <stdlib.h>
void funkcja() {
int sumaNiep = 0;
int sumaPa = 0;
int userInput = 1;
int iPa = 0;
int iNiep = 0;
int i = 0;
while(1) {
printf("%d. Podaj calkowita liczbe: ", ++i);
if(scanf(" %d", &userInput) != 1 || userInput == 0) break; // break out
// jesli parzysta
if(userInput % 2 == 0) {
sumaPa += userInput;
++iPa; // count evens
} else {
sumaNiep += userInput;
++iNiep; // count odds
}
}
if(iPa) { // avoid div by zero
double sredniaPa = (double)sumaPa / iPa; // double div
printf("srednia parzysta %d / %d : %lf\n", sumaPa, iPa, sredniaPa);
}
if(iNiep) { // avoid div by zero
double sredniaNiep = (double)sumaNiep / iNiep; // double div
printf("srednia parzysta %d / %d : %lf\n", sumaNiep, iNiep, sredniaNiep);
}
}
The problem was I divided by the number of all digits (odd and even) to calculate both averages. Here is improved code:
#include <stdio.h>
#include <stdlib.h>
void funkcja()
{
int sumaNiep = 0;
int sumaPa = 0;
int userInput = 1;
int i_p = 0, i_np = 0;
while(userInput != 0)
{
//wprow zmiennej
printf("%d. Podaj calkowita liczbe: ", i_p+i_np+1);
scanf("%d", &userInput);
//jesli parzysta
if (userInput % 2 == 0)
{
sumaPa += userInput;
if (userInput != 0)
{
i_p++;
}
} else {
sumaNiep += userInput;
i_np++;
}
}
if (i_np != 0)
{
double sredniaNiep = sumaNiep/(i_np);
printf("\nSrednia nieparzysta %d / %d : %lf", sumaNiep, i_np, sredniaNiep);
}
if (i_p != 0)
{
double sredniaPa = sumaPa/(i_p);
printf("\nSrednia parzysta %d / %d : %lf", sumaPa, i_p, sredniaPa);
}
}
int main()
{
funkcja();
}
I have followed everything in the book, yet my average score fails me, every single time. I have debugged my program multiple times, in vain.
My minimal executable code:
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define MAX_TESTS 5
#define MAXQUESTION 10000
bool myread(const char * format, void * address) {
char buffer[1024];
fgets(buffer, sizeof buffer, stdin);
return sscanf(buffer, format, address) == 1;
}
struct struc {
int a;
int b;
int c;
int add;
int grade;
};
int sj(int n) {
int t;
t = rand() % n;
return t;
}
void ctm_i(struct struc * t) {
{
t -> a = sj(101);
t -> c = sj(4);
if (t -> c == 1) {
t -> b = sj(101 - (t -> a));
t -> add = (t -> a) + (t -> b);
} else {
t -> b = sj((t -> a) + 1);
t -> add = (t -> a) - (t -> b);
}
t -> grade = 0;
}
}
void tcm_i(struct struc * t, int n) {
int ad;
printf(" ***********************************************************************"
"*********\n");
printf(" ......................................................................."
".........\n");
printf(" Question %d\n\n", n + 1);
printf(" You have 3 attempts for this question\n\n");
if (t -> c == 1)
printf(" %d+%d= ", t -> a, t -> b);
else
printf(" %d-%d= ", t -> a, t -> b);
myread(" %d", & ad);
if (ad == t -> add)
{
t -> grade = 10;
printf(" You earned 10 marks\n\n");
} else {
printf("\n Incorrect, you have 2 attempts remaining\n\n");
printf(" ");
myread(" %d", & ad);
if (ad == t -> add)
{
t -> grade = 7;
printf(" You earned 7 marks\n\n");
} else {
printf("\n Incorrect, you have 1 attempt remaining\n\n");
printf(" ");
myread(" %d", & ad);
if (ad == t -> add)
{
t -> grade = 5;
printf(" You earned 5 marks\n\n");
} else {
t -> grade = 0;
printf("\n Failure, 0 mark\n\n");
printf("\n The correct answer is %d\n\n", t -> add);
}
}
}
printf(" ......................................................................."
".........\n");
printf(" ***********************************************************************"
"*********\n");
}
void quiz(char name[]) {
int rounds = 0;
int highest = 0;
int lowest = INT_MAX;
float allScore = 0;
float avg = 0.0;
int i, j, g = 0;
struct struc test[MAX_TESTS];
srand((unsigned) time(NULL));
for (;;) {
rounds++;
for (i = 0; i < MAX_TESTS; i++) // generate all questions
{
ctm_i( & test[i]);
for (j = 0; j < i; j++)
if (test[i].a == test[j].a && test[i].b == test[j].b && test[i].c == test[j].c)
//if question is already present
ctm_i( & test[i]); //then re-generate
}
printf("\n Are you ready? Press Enter key to continue. ");
myread("", NULL);
for (i = 1; i <= 5; i++) {
printf(" *******************************************************************"
"**"
"***********\n");
printf(" ..................................................................."
".."
"...........\n");
}
// Take quiz
for (i = 0; i < MAX_TESTS; i++)
tcm_i( & test[i], i);
printf(" End\n\n");
bool done = false;
bool unsure = true;
bool showS = true;
while (unsure) {
unsure = false;
puts("\n");
if (showS) {
puts(" Enter 'S' to show results");
}
puts(" Enter 'P' to play another round");
puts(" Enter 'R' to return to main menu");
char choice;
printf(" ");
myread(" %c", & choice);
printf("\n");
if (choice == 'r' || choice == 'R') {
done = true;
} else {
///////////////////////// Changes /////////////
g = 0;
// calculate total score for current round
for (i = 0; i < MAX_TESTS; i++) {
g += test[i].grade; //add score of each question
}
allScore += g; //add current round's score to total
avg = allScore / rounds; //average of all rounds
if (g > highest) {
highest = g;
}
if (g < lowest) {
lowest = g;
}
if (choice == 'S' || choice == 's') {
showS = false;
if (rounds == 1) {
printf(" Final score: %d/100\n", g); //display round score
printf(" ****** Player: %s ******\n", name);
} else {
printf(" Round %d score: %d/100\n", rounds, g); //display round score
printf(" Highest score: %d/100\n", highest);
printf(" Lowest score : %d/100\n", lowest);
printf(" Average score: %f/100\n", avg);
printf(" ****** Player: %s ******\n", name);
}
unsure = true;
} else if (choice == 'P' || choice == 'p') {
/// nothing to be done here
//we will display next test
} else {
puts(" Invalid input!");
unsure = true;
}
////////////////////////////////////
}
}
if (done)
break;
}
}
int main() {
char i1 = '1';
char name[25]; // ig;
printf("\n Welcome");
printf("\n");
while (i1 != 0) {
printf("\n");
//printf(" **********************Welcome %s! *********************\n", name);
printf(" ************************ Main Menu of Maths Quiz ***************************\n");
printf(" * 1.Enter Quiz *\n");
printf(" * 2.Quit *\n");
printf(" ****************************************************************************\n");
printf(" Please choose one from 1-2:\n");
printf(" ");
myread(" %c", & i1);
switch (i1) {
case '1':
printf("\n Enter Quiz:\n");
quiz(name); // calling quiz function defined in file "maincode.c"
break;
case '2':
printf(" Quit.\n\n");
}
}
return 0;
}
Hope that fulfilled the definition of an MRE.
So I have snipped off some bombastic lines, and the ones left are the important ones, I think.
The problem is in your function quiz, and in particular in the while (unsure) loop. In this loop, you add the most recent score to the running total:
allScore += g; //add current round's score to total
This should happen once per round played. But if the user inputs "S" or something invalid, your program sets
unsure = true;
which means the loop will run again, before the next round is played. It then adds the most recent score a second time to the grand total.
The most logical solution would be to move all the calculations of totals, maximum, minimum, average out of the while-loop. The loop serves a different purpose: it is for user interaction and reporting, not for processing results.
possible chance of multiple avg calculation for same round again. Keep flag to track accounting of score, so we will not do the same more than once till the game is not played again.
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define MAX_TESTS 5
#define MAXQUESTION 10000
bool myread(const char * format, void * address) {
char buffer[1024];
fgets(buffer, sizeof buffer, stdin);
return sscanf(buffer, format, address) == 1;
}
struct struc {
int a;
int b;
int c;
int add;
int grade;
};
int sj(int n) {
int t;
t = rand() % n;
return t;
}
void ctm_i(struct struc * t) {
{
t -> a = sj(101);
t -> c = sj(4);
if (t -> c == 1) {
t -> b = sj(101 - (t -> a));
t -> add = (t -> a) + (t -> b);
} else {
t -> b = sj((t -> a) + 1);
t -> add = (t -> a) - (t -> b);
}
t -> grade = 0;
}
}
void tcm_i(struct struc * t, int n) {
int ad;
printf(" ***********************************************************************"
"*********\n");
printf(" ......................................................................."
".........\n");
printf(" Question %d\n\n", n + 1);
printf(" You have 3 attempts for this question\n\n");
if (t -> c == 1)
printf(" %d+%d= ", t -> a, t -> b);
else
printf(" %d-%d= ", t -> a, t -> b);
myread(" %d", & ad);
if (ad == t -> add)
{
t -> grade = 10;
printf(" You earned 10 marks\n\n");
} else {
printf("\n Incorrect, you have 2 attempts remaining\n\n");
printf(" ");
myread(" %d", & ad);
if (ad == t -> add)
{
t -> grade = 7;
printf(" You earned 7 marks\n\n");
} else {
printf("\n Incorrect, you have 1 attempt remaining\n\n");
printf(" ");
myread(" %d", & ad);
if (ad == t -> add)
{
t -> grade = 5;
printf(" You earned 5 marks\n\n");
} else {
t -> grade = 0;
printf("\n Failure, 0 mark\n\n");
printf("\n The correct answer is %d\n\n", t -> add);
}
}
}
printf(" ......................................................................."
".........\n");
printf(" ***********************************************************************"
"*********\n");
}
void quiz(char name[]) {
int rounds = 0;
int highest = 0;
int lowest = INT_MAX;
float allScore = 0;
float avg = 0.0;
int i, j, g = 0;
struct struc test[MAX_TESTS];
srand((unsigned) time(NULL));
for (;;) {
rounds++;
for (i = 0; i < MAX_TESTS; i++) // generate all questions
{
ctm_i( & test[i]);
for (j = 0; j < i; j++)
if (test[i].a == test[j].a && test[i].b == test[j].b && test[i].c == test[j].c)
//if question is already present
ctm_i( & test[i]); //then re-generate
}
printf("\n Are you ready? Press Enter key to continue. ");
myread("", NULL);
for (i = 1; i <= 5; i++) {
printf(" *******************************************************************"
"**"
"***********\n");
printf(" ..................................................................."
".."
"...........\n");
}
// Take quiz
for (i = 0; i < MAX_TESTS; i++)
tcm_i( & test[i], i);
printf(" End\n\n");
bool done = false;
bool unsure = true;
bool showS = true;
bool acct = false;
while (unsure) {
unsure = false;
puts("\n");
if (showS) {
puts(" Enter 'S' to show results");
}
puts(" Enter 'P' to play another round");
puts(" Enter 'R' to return to main menu");
char choice;
printf(" ");
myread(" %c", & choice);
printf("\n");
if (choice == 'r' || choice == 'R') {
done = true;
} else {
///////////////////////// Changes /////////////
if (false == acct) {
g = 0;
// calculate total score for current round
for (i = 0; i < MAX_TESTS; i++) {
g += test[i].grade; //add score of each question
}
allScore += g; //add current round's score to total
avg = allScore / rounds; //average of all rounds
if (g > highest) {
highest = g;
}
if (g < lowest) {
lowest = g;
}
acct = true;
}
if (showS &&(choice == 'S' || choice == 's')) {
showS = false;
if (rounds == 1) {
printf(" Final score: %d/100\n", g); //display round score
printf(" ****** Player: %s ******\n", name);
} else {
printf(" Round %d score: %d/100\n", rounds, g); //display round score
printf(" Highest score: %d/100\n", highest);
printf(" Lowest score : %d/100\n", lowest);
printf(" Average score: %f/100\n", avg);
printf(" ****** Player: %s ******\n", name);
}
unsure = true;
} else if (choice == 'P' || choice == 'p') {
/// nothing to be done here
//we will display next test
} else {
puts(" Invalid input!");
unsure = true;
}
////////////////////////////////////
}
}
if (done)
break;
}
}
int main() {
char i1 = '1';
char name[25]; // ig;
printf("\n Welcome");
printf("\n");
while (i1 != 0) {
printf("\n");
//printf(" **********************Welcome %s! *********************\n", name);
printf(" ************************ Main Menu of Maths Quiz ***************************\n");
printf(" * 1.Enter Quiz *\n");
printf(" * 2.Quit *\n");
printf(" ****************************************************************************\n");
printf(" Please choose one from 1-2:\n");
printf(" ");
myread(" %c", & i1);
switch (i1) {
case '1':
printf("\n Enter Quiz:\n");
quiz(name); // calling quiz function defined in file "maincode.c"
break;
case '2':
printf(" Quit.\n\n");
}
}
return 0;
}
Output:
Enter 'S' to show results
Enter 'P' to play another round
Enter 'R' to return to main menu
s
Round 2 score: 47/100
Highest score: 50/100
Lowest score : 47/100
Average score: 48.500000/100
****** Player: ******
So I am writing a gambling program for my c programming class. Essential its a menu for a dog track and you have to place a wager, select a dog, and the program chooses a winner and tells you if you won (how much) or lost. I use the ran() function but a specific dog that I set to win 10% of the time wins more than any other dog (including one that should win 40% of the time).
/*Programmer: John S. Bolen*/
/*Date: 3/1/19*/
/* User Will Choose to gamble, View Results, Or Quit program.
There are 9 Dogs to Chose from with a set %chance to win and
a set Payout Rate */
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <ctype.h>
#define SIZE 1000
#define PAUSE system("pause")
#define CLS system("cls")
#define FLUSH nothingFlush()
#define SIZE 1000
void nothingFlush() {
char nothing;
while (scanf("%c", ¬hing) == NULL);
}
typedef struct {
char name[100];
float payout;
float winOdds;
} DOG;
//Prototype Functions
void displayAllRaces(DOG dog[], int winners[], int counter, int countOne,
int countTwo, int countThree, int countFour, int countFive, int countSix,
int countSeven, int countEight, int countNine);
void displayMenu();
void getBet(float *bet);
char getChoice();
float getOdds();
void pickDog(DOG dog[], int *counter, int winners[], float *bet, int *countOne,
int *countTwo, int *countThree, int *countFour, int *countFive, int *countSix,
int *countSeven, int *countEight, int *countNine);
main() {
char userChoice;
DOG dog[SIZE];
int counter = 0;
int countOne = 0, countTwo = 0, countThree = 0, countFour = 0,
countFive = 0, countSix = 0, countSeven = 0, countEight = 0,
countNine = 0;
int winners[SIZE] = { 0 };
float bet = 0;
do {
userChoice = getChoice();
switch (userChoice) {
case 'G': // Gamble
getBet(&bet);
pickDog(dog, &counter, winners, &bet, &countOne, &countTwo, &countThree,
&countFour, &countFive, &countSix, &countSeven, &countEight, &countNine);
break;
case 'R': //Results
displayAllRaces(dog, winners,counter, countOne, countTwo, countThree, countFour,
countFive, countSix, countSeven, countEight, countNine);
break;
case 'L': //Leave
printf("\n\tThank you for visiting the Dog Track\n");
break;
default:
printf("\n\tERROR! -- Enter A Valid Selection...\n");
break;
}//End Switch
PAUSE;
} while (userChoice != 'L');
}
void displayAllRaces(DOG dog[], int winners[], int counter, int countOne,
int countTwo, int countThree, int countFour, int countFive, int countSix,
int countSeven, int countEight, int countNine) {
int i = 0;
CLS;
printf("\n\tRace Results: \n");
printf("\tDog\t\t\t\t\tNum of Wins\n");
if (counter > 0) {
printf("\t%s\t\t\t%i\n", dog[0].name, countOne);
printf("\t%s\t\t\t%i\n", dog[1].name, countTwo);
printf("\t%s\t\t%i\n", dog[2].name, countThree);
printf("\t%s\t\t%i\n", dog[3].name, countFour);
printf("\t%s\t\t%i\n", dog[4].name, countFive);
printf("\t%s\t\t%i\n", dog[5].name, countSix);
printf("\t%s\t\t%i\n", dog[6].name, countSeven);
printf("\t%s\t\t\t%i\n", dog[7].name, countEight);
printf("\t%s\t\t\t%i\n", dog[8].name, countNine);
}
else {
printf("\n\t\n");
}
}
void displayMenu(){
CLS;
printf("\n\t==================================================\n");
printf("\n\t== MAIN MENU ==\n");
printf("\n\t==================================================\n");
printf("\n\t[G]amble\n");
printf("\n\t[R]esults\n");
printf("\n\t[L]eave\n");
printf("\n\tEnter Your Selection: ");
}
void getBet(float *bet) {
float result = 0;
printf("\n\tEnter the amount you want to gamble: ");
printf("\n\t(Bet has to be between $1 and $1000)\n");
scanf_s("%f", &result); FLUSH;
if(result < 1 || result > 1000){
printf("\n\tERROR-- Please enter a valid amount\n");
printf("\n\tEnter the amount you want to gamble: ");
printf("\n\t(Bet has to be between $1 and $1000)\n");
scanf_s("%f", &result); FLUSH;
}
printf("\n\tThank you for placing your wager.\n\tGood luck!\n");
*bet = result;
PAUSE;
}
char getChoice() {
char result;
displayMenu();
scanf_s("%c", &result); FLUSH;
result = toupper(result);
return result;
}
float getOdds() {
float odds[9] = { 40, 10, 8, 6, 1, 4, 8, 10, 13 };
return odds[9];
}
void pickDog(DOG dog[], int *counter, int winners[], float *bet, int *countOne,
int *countTwo, int *countThree, int *countFour, int *countFive, int *countSix,
int *countSeven, int *countEight, int *countNine) {
int i = 0;
int choice;
float betMoney = 0;
int winner = 0;
CLS;
printf("\n\tPick a dog from the list:");
strcpy(dog[0].name, "\n\t1.Gandalf the Great");
strcpy(dog[1].name, "\n\t2.Fenrir Greyback");
strcpy(dog[2].name, "\n\t3.Marley the Magnificent");
strcpy(dog[3].name, "\n\t4.Clifford the Big Red Dog");
strcpy(dog[4].name, "\n\t5.Petey the Little Rascal");
strcpy(dog[5].name, "\n\t6.Courage the Cowardly Dog");
strcpy(dog[6].name, "\n\t7.Old Yeller Before the Bullet");
strcpy(dog[7].name, "\n\t8.Pongo the Dalmatian");
strcpy(dog[8].name, "\n\t9.Nymeria Stark\n");
for (i = 0; i < 9; i++) {
printf("%s", dog[i].name);
}
printf("\n");
scanf_s("%i", &choice); FLUSH;
do {
if (choice < 1 || choice > 9) {
printf("\n\tPlease, try again...\n");
scanf_s("%i", &choice);
}
} while (choice < 1 || choice > 9);
betMoney = *bet;
winner = 1 + rand() % (100 - 1 + 1);
if (winner <= 40) {
winner = 1;
(*countOne)++;
}
else if (winner <= 50) {
winner = 2;
(*countTwo)++;
}
else if (winner <= 48) {
winner = 3;
(*countThree)++;
}
else if (winner <= 64) {
winner = 4;
(*countFour)++;
}
else if (winner <= 65) {
winner = 5;
(*countFive)++;
}
else if (winner <= 69) {
winner = 6;
(*countSix)++;
}
else if (winner <= 77) {
winner = 7;
(*countSeven)++;
}
else if (winner <= 87) {
winner = 8;
(*countEight)++;
}
else if (winner <= 100) {
winner = 9;
(*countNine)++;
}
winners[*counter] = winner;
(*counter)++;
if (choice == winner) {
printf("\n\tYou picked a WINNER!\n");
if (winner == 1) {
(*bet) = betMoney * 2;
printf("You win $%.2f\n", *bet);
}
if (winner == 2) {
(*bet) = betMoney * 5;
printf("You win $%.2f\n", *bet);
}
if (winner == 3) {
(*bet) = betMoney * 10;
printf("You win $%.2f\n", *bet);
}
if (winner == 4) {
(*bet) = betMoney * 15;
printf("You win $%.2f\n", *bet);
}
if (winner == 5) {
(*bet) = betMoney * 50;
printf("You win $%.2f\n", *bet);
}
if (winner == 6) {
(*bet) = betMoney * 20;
printf("You win $%.2f\n", *bet);
}
if (winner == 7) {
(*bet) = betMoney * 10;
printf("You win $%.2f\n", *bet);
}
if (winner == 8) {
(*bet) = betMoney * 5;
printf("You win $%.2f\n", *bet);
}
if (winner == 9) {
(*bet) = betMoney * 3;
printf("You win $%.2f\n", *bet);
}
}
else {
printf("\n\tYou picked a LOSER!\n");
(*bet) = (*bet) - betMoney;
}
}
I have included the entire code for my program here (so you can test it if you wish), but only need help in fixing my rand() function. As you can see I want to randomly chose a number between 1-100. If the number is <= 40 then its dog one 40% chance to win, if the number is <= 50 (meaning its <= 50 but >40)then dog 2 wins with a 10% chance to win. I have run the program numerous times and dog 2 always seems to have the most wins after I run it x amount of times. Any help or suggestions would be greatly appreciated!
I am working on writing a code for the game, Mancala, and testing along the way. So far, I am getting an error that says:
Segmentation Fault (core dumped)
I'm not sure how to fix it and keep it running.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void move_clockwise(int board[], int pos, int player_1);
void move_count_clock(int board[], int pos, int player_1);
void mancala_board(int board[]);
int *current1;
int *current2;
int board[30], player_1, sum, position, direction, i, n, play, initPos, curPos, pos;
//======================================================================
int main(void)
{
int board[30];
board[0] = 4;
board[1] = 4;
board[2] = 4;
board[3] = 4;
board[4] = 4;
board[5] = 4;
board[6] = 0;
board[7] = 4;
board[8] = 4;
board[9] = 4;
board[10] = 4;
board[11] = 4;
board[12] = 4;
board[13] = 0;
printf("Welcome to Mancala\n");
printf("\n\n 5 4 3 2 1 0 \n");
printf("BLUE\n");
printf("=====[%d] [%d] [%d] [%d] [%d] [%d]-----\n", board[5], board[4], board[3], board[2], board[1], board[0]);
printf("|%d| |%d|\n", board[6], board[13]);
printf("-----[%d] [%d] [%d] [%d] [%d] [%d]=====\n", board[7], board[8], board[9], board[10], board[11], board[12]);
printf(" RED\n");
printf(" 6 7 8 9 10 11 \n\n");
sum=board[6]+board[13];
player_1=first_player();
while(sum!=48)
{
while (player_1 == 1)
{
printf("Player RED\n");
printf("Pick a position corresponding to the integer: ");
scanf("%d", position);
while (position!=6 || position!=7 || position!=8 || position!=9 || position!=10 || position!=11)
{
printf("\nInvalid input, you have to select a bowl from your side.\nPlease select another position");
scanf("%d",&position);
}
printf("Would you like to move clockwise or counter-clockwise?");
printf("\n1. Clockwise \n2. Counter-Clockwise");
scanf("%d",&direction);
while(direction!=1 && direction!=2)
{
printf("\nInvalid input, you have to select an integer corresponding to the given options.\n");
printf("\n1. Clockwise \n2. Counter-Clockwise");
scanf("%d",&direction);
}
if (direction==1)
{
position+=1;
move_clockwise(board, position, player_1);
}
if(direction==2)
{
position=+1;
move_count_clock(board, position, player_1);
}
player_1-=1;
mancala_board(board);
}
if (player_1 == 0)
{
printf("Player BLUE\n");
printf("Pick a position corresponding to the integer: ");
scanf("%d", position);
while (position!=0 || position!=1 || position!=2 || position!=3 || position!=4 || position!=5)
{
printf("\nInvalid input, you have to select a bowl from your side.\nPlease select another position");
scanf("%d",&position);
}
printf("Would you like to move clockwise or counter-clockwise?");
printf("\n1. Clockwise \n2. Counter-Clockwise");
scanf("%d",&direction);
while(direction!=1 && direction!=2)
{
printf("\nInvalid input, you have to select an integer corresponding to the given options.\n");
printf("\n1. Clockwise \n2. Counter-Clockwise");
scanf("%d",&direction);
}
if (direction==1)
{
position+=1;
move_clockwise(board, position, player_1);
}
if(direction==2)
{
position=+1;
move_count_clock(board, position, player_1);
}
player_1+=1;
mancala_board(board);
}
sum=board[6]+board[13];
}
}
//======================================================================
int first_player(void)
{
//to determine who will be player 1
play=rand()%2;
return (play);
}
//======================================================================
//Display current board
void mancala_board(int board[])
{
printf("\n\n 5 4 3 2 1 0 \n");
printf("BLUE\n");
printf("=====[%d] [%d] [%d] [%d] [%d] [%d]-----\n", board[5], board[4], board[3], board[2], board[1], board[0]);
printf("|%d| |%d|\n", board[6], board[13]);
printf("-----[%d] [%d] [%d] [%d] [%d] [%d]=====\n", board[7], board[8], board[9], board[10], board[11], board[12]);
printf(" RED\n");
printf(" 6 7 8 9 10 11 \n\n");
}
//======================================================================
//allow player to move again if late marble lands in mancala
//void move_again(int board[], int pos, int player_1)
//{
//}
//======================================================================
//captures the marbles across the current position if player's
//last marble lands on their own bowl with no marbles in
//void capture()
//{
//}
//======================================================================
void move_clockwise(int board[], int pos, int player_1)
{
initPos = pos;
n=board[pos];
pos+=1;
for (i = 0; i < n ; i++)
{
curPos +=1;
board[curPos]+=1;
if (curPos == 14)
curPos -=14;
else if (curPos >= 28)
curPos -= 28;
if (player_1 == 0)
{
current1 = &(board[curPos]);
if (current1 == &(board[6]))
{
current1 = &(board[7]);
current1 += 1;
}
}
if (player_1 == 1)
{
current2 = &(board[curPos]);
if (current2 == &(board[13]))
{
current2 = &(board[0]);
current2 += 1;
}
}
}
board[initPos] = 0;
}
//======================================================================
void move_count_clock(int board[], int pos, int player_1)
{
initPos = pos;
n=board[pos];
pos+=1;
for (i = 0; i < n ; i++)
{
curPos +=1;
board[curPos]+=1;
if (curPos == 14)
curPos -=14;
else if (curPos >= 28)
curPos -= 28;
if (player_1 == 0)
{
current1 = &(board[curPos]);
if (current1 == &(board[6]))
{
current1 = &(board[7]);
current1 += 1;
}
}
if (player_1 == 1)
{
current2 = &(board[curPos]);
if (current2 == &(board[13]))
{
current2 = &(board[0]);
current2 += 1;
}
}
}
board[initPos] = 0;
}
Maybe you want to separate the code in smaller pieces and test each piece. Or maybe this can help you: http://ericlippert.com/2014/03/05/how-to-debug-small-programs/
To put & inside scanf is correct suggestion, I think that was meant in the comment.
Anyway, this is also weird:
while (position!=6 || position!=7 || position!=8 || position!=9 || position!=10 || position!=11)
{
scanf("%d",&position);
}
what do you expect above? It will always enter that loop, and never come out, since
if position is 6 it can't be 7 hence due to OR the statement will be true.
I'm new to programming and I had to work on a program that would simulate 10,000 games of craps. I got it to calculate points for house and player just fine until I added in the function "diceRoll" where player rolls again and again until it matches the first roll or 7 (house wins). Now it gives decidedly not random results (such as the house winning 0 times out of 10,000). What did I do wrong?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
bool diceRoll (int a)
{
srand( (unsigned)time(NULL));
int n = 0;
int b = 0;
while(n < 1) {
b = rand() % 12;
if(b == a || b == 6) n++;
}
if(b == 6) return false;
else return true;
}
int main (void)
{
srand( (unsigned)time(NULL));
int a, n, house, player, point;
house = 0;
player = 0;
point = 0;
for(n = 0; n < 10000; n++) {
a = rand() % 12;
if(a == 1 || a == 2 || a == 11) {
house++;
}
else if(a == 6 || a == 10) {
player++;
}
else {
if(diceRoll(a) == true) player++;
else house++;
}
}
printf("The house has %i points.\n", house);
printf("The player has %i points.\n", player);
return 0;
}
You've over-seeded, remove the call to srand() in diceRoll and you should be fine (this ignores bias due to modulo usage).
Only seed in main() (and not in a loop) and don't seed it in the diceRoll(a) function.
I ran it your way and got house = 2, player = 9998.
Removing the srand((unsigned)time(null)); in the diceroll(a) came back with:
The house has 5435 points
The player has 4565 points
I assume that is what you wanted
bool diceRoll (int a)
{
int n = 0;
int b = 0;
while(n < 1) {
b = rand() % 12;
if(b == a || b == 6) n++;
}
if(b == 6) return false;
else return true;
}
int main (void)
{
srand( (unsigned)time(NULL));
int a, n, house, player, point;
house = 0;
player = 0;
point = 0;
for(n = 0; n < 10000; n++) {
a = rand() % 12;
if(a == 1 || a == 2 || a == 11) {
house++;
}
else if(a == 6 || a == 10) {
player++;
}
else {
if(diceRoll(a) == true) player++;
else house++;
}
}
printf("The house has %i points.\n", house);
printf("The player has %i points.\n", player);
return 0;
}