Basically I am supposed to simulate a program that rolls three dice, add it up. Then I will have the user guess if the next roll is higher, lower, same or if they just want to quit. I am having two problems.
The numbers are not random, obviously this is a big mistake on my part but I can't seem to figure it out. I am thinking I do not need the second inclusion of 3 dice pairs? They don't help at all anyways.
Regardless, my program goes through all of the if/else if statements all at once. Obviously I do not want this to happen.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
int diceOne, diceTwo, diceThree, diceSum=0, timesCorrect=0, choice;
int newDiceOne, newDiceTwo, newDiceThree, newDiceSum;
srand( time(NULL) );
diceOne = rand() % 6 + 1;
diceTwo = rand() % 6 + 1;
diceThree = rand() % 6 + 1;
newDiceOne = rand() % 6 + 1;
newDiceTwo = rand() % 6 + 1;
newDiceThree = rand() % 6 + 1;
printf("The three dice rolls: %d, %d, %d", diceOne, diceTwo, diceThree);
diceSum = diceOne + diceTwo + diceThree;
printf("\nTotal sum of dice is %d\n", diceSum);
do {
printf("Guess higher(1), lower(2), same(3) or quit?(4)\n");
printf(" You have been correct %d times\n", timesCorrect);
scanf("%d", &choice);
printf("The three dice rolls: %d, %d, %d", newDiceOne, newDiceTwo, newDiceThree);
newDiceSum= newDiceOne + newDiceTwo + newDiceThree;
printf("\nTotal sum of dice is %d\n", newDiceSum);
if (choice == 1)
{
if (newDiceSum > diceSum);
timesCorrect++;
printf("You are correct!\n");
}
else if (newDiceSum < diceSum);
{
printf("You are incorrect, sorry!\n");
}
if (choice == 2)
{
if (newDiceSum < diceSum);
timesCorrect++;
printf("You are correct!\n");
}
else if (newDiceSum > diceSum);
{
printf("You are incorrect, sorry!\n");
}
if (choice == 3)
{
if (newDiceSum == diceSum);
timesCorrect ++;
printf("You are correct!\n");
}
else if (newDiceSum != diceSum);
{
printf("You are incorrect, sorry!\n");
}
if (choice == 4)
{
printf("Thanks for playing!!!!!!\n");
system("pause");
return 0;
}
} while (choice!= 4 );
}
You have an extra semicolon after the else if conditionals, like here
else if (newDiceSum < diceSum);
/* ^ this should not be here */
If you use a compiler with good diagnostic capabilities and enable warnings, it should warn you about that "typo", if you want to leave the block empty use braces like
else if (newDiceSum < diceSum) {}
Also, you set the first dice with rand() and they are random values, but then you always use the same values in the loop.
The following code:
Handles error conditions
Eliminates unneeded variables
Cleanly compiles
Executes with out failing
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ( void )
{
int diceOne;
int diceTwo;
int diceThree;
int diceSum=0;
int timesCorrect=0;
int choice;
int newDiceSum;
srand( time(NULL) );
diceOne = rand() % 6 + 1;
diceTwo = rand() % 6 + 1;
diceThree = rand() % 6 + 1;
printf("The three dice rolls: %d, %d, %d", diceOne, diceTwo, diceThree);
diceSum = diceOne + diceTwo + diceThree;
printf("\nTotal sum of dice is %d\n", diceSum);
do {
printf("Guess higher(1), lower(2), same(3) or quit?(4)\n");
printf(" You have been correct %d times\n", timesCorrect);
if( 1 != scanf("%d", &choice) )
{ // then scanf failed
perror( "scanf for choice failed" );
exit( EXIT_FAILURE );
}
// implied else, scanf successful
diceOne = rand() % 6 + 1;
diceTwo = rand() % 6 + 1;
diceThree = rand() % 6 + 1;
printf("The three dice rolls: %d, %d, %d", diceOne, diceTwo, diceThree);
newDiceSum = diceOne + diceTwo + diceThree;
printf("\nTotal sum of dice is %d\n", newDiceSum);
switch( choice )
{
case 1:
if (newDiceSum > diceSum)
{
timesCorrect++;
printf("You are correct!\n");
}
else
{
printf("You are incorrect, sorry!\n");
}
break;
case 2:
if (newDiceSum < diceSum)
{
timesCorrect++;
printf("You are correct!\n");
}
else
{
printf("You are incorrect, sorry!\n");
}
break;
case 3:
if (newDiceSum == diceSum)
{
timesCorrect ++;
printf("You are correct!\n");
}
else
{
printf("You are incorrect, sorry!\n");
}
break;
case 4:
printf("Thanks for playing!!!!!!\n");
system("pause");
break;
default:
printf( " invalid choice, valid choices are 1...4\n");
break;
} // end switch
} while (choice!= 4 );
return(0);
} // end function: main
Related
void main() {
int low, high, odds = 0;
do {
printf("Please enter a number:");
rewind(stdin);
scanf("%d", &low);
} while (low <= 0);
do {
printf("Please enter the second number:");
rewind(stdin);
scanf("%d", &high);
} while (high < 2 * low);
printf("The odd numbers between %d and %d are: ", low, high);
for (odds = low;odds <= high;odds++) {
if (odds % 2 != 0)
{
printf(" %d", odds);
}
}
printf(".\n");
system("pause"); }
I enter the input which '1' for 'low' variable while '10' for 'high' variable then it shows the result: "The odd numbers between 1 and 10 are 1 3 5 7 9. ".So, how can I improve or change my code by printing output:"The odd ..... 1,3,5,7,9."?
To add commas
int first = 1;
for (odds = low;odds <= high;odds++) {
if (odds % 2 != 0)
{
if(first){ // to prevent comma before first number
first = 0;
} else {
printf("%s",",");
}
printf(" %d", odds);
}
}
could have been
printf("%c", ',');
. Ie a single character, but I used %s just in case you want to add more padding
One nice thing about odd numbers is that you know exactly where they are. Rather that iterating over all the values and checking if each is odd, just find the first odd value and increment by 2:
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char **argv)
{
int low = argc > 1 ? strtol(argv[1], NULL, 10) : 1;
int high = argc > 2 ? strtol(argv[2], NULL, 10) : 10;
printf("The odd numbers between %d and %d are: ", low, high);
if( low % 2 == 0 ){
low += 1;
}
for( int odd = low; odd <= high; odd += 2 ){
printf("%s%d", odd == low ? "" : ", ", odd);
}
putchar('.');
putchar('\n');
return 0;
}
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();
}
Basically this is a program to play with dice but i have a problem with srand. it gives an error stating "implicit conversion loses integer precision: 'time_t' (aka 'long') to 'unsigned int'"
whys that ?
Also i would like to know if there are any other ways to improve this code? currently i only know stdio.h i know there are some out there like iostream or something like that. is there a possible way to explain those to me also.
Here is the code.
i know crt secure no warning is to ignore some errors but i would still like to know why it the error pops up ?
#define _CRT_SECURE_NO_WARNINGS
#define MAX_CHIPS 400
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void display_details(void);
int throws_die(void);
int main() so on
{
int die1, die2, throw_sum;
int PointToMake;
int Games_Played = 0;
int Games_Won = 0;
int Games_Lost = 0;
int CurrentChips = MAX_CHIPS;
int BetChips;
char PlayerName[30];
char PlayAgain;
display_details();
srand(time(NULL));
printf("Would you like to play Test your luck [y|n]?\n");
scanf(" %c", &PlayAgain);
while ((PlayAgain == 'y') && (CurrentChips > 0))
{
if (Games_Played == 0)//shows how many games played which is obviously 0
{
printf("A new chellenger! What is your name?\n");
scanf(" %s", &PlayerName);
printf("Hi %s!\n", PlayerName);
}
Games_Played = Games_Played + 1;//each new game it will increase by 1
printf("Number of chips: %d\n", CurrentChips);
printf("Place your bet:\n ");
scanf("%d", &BetChips);
while ((BetChips < 0) || (BetChips > CurrentChips))
{
printf("uuh ....You can only bet the chips you have.. (0-%d)!\n", CurrentChips);
printf("Place your bet: \n");
scanf("%d", &BetChips);
}
die1 = throws_die();
die2 = throws_die();
throw_sum = die1 + die2;
printf("You Got: %d + %d = %d\n", die1, die2, throw_sum);
if ((throw_sum == 7) || (throw_sum == 12))
{
//+1 to games won
Games_Won = Games_Won + 1;
//adding to bet balance
CurrentChips = CurrentChips + BetChips;
printf("XXXXX Winner! d(^_^) XXXXX\n");
}
else if ((throw_sum == 2) || (throw_sum == 3) || (throw_sum == 10))
{
Games_Lost = Games_Lost + 1;
CurrentChips = CurrentChips - BetChips;
printf("XXXXX Loser! :( XXXXX\n");
}
else
{
PointToMake = throw_sum;
printf("Points to make is: %d\n", PointToMake);
die1 = throws_die();
die2 = throws_die();
throw_sum = die1 + die2;
printf(" |--->> Spinned: %d + %d = %d\n", die1, die2, throw_sum);
while (throw_sum != PointToMake && throw_sum != 7)
{
die1 = throws_die();
die2 = throws_die();
throw_sum = die1 + die2;
printf(" |--->> Spinned: %d + %d = %d\n", die1, die2, throw_sum);
}
if (throw_sum == PointToMake)
{
printf("XXXXX Winner! (x2 the bet) XXXXX\n");
//x2 added to balance
CurrentChips = CurrentChips + 2 * BetChips;
Games_Won = Games_Won + 1;
}
else
{
Games_Lost = Games_Lost + 1;
CurrentChips = CurrentChips - BetChips;
printf("XXXXX Loser!:( XXXXX\n");
}
}
if (CurrentChips > 0)
{
printf("You now have %d chips.\n", CurrentChips);
printf("============================\n\n");
printf("Play Again %s [y|n]? ", PlayerName);
scanf(" %c", &PlayAgain);
printf("============================\n");
}
else
{
printf("you're out of chips.\n");
printf("XXXXX GG TRY AGAIN NEXT TIME XXXXX\n");
}
}
if (Games_Played == 0)
{
printf("Oh well.... better luck next time!\n");
}
else if (Games_Played == 1)
{
printf("%s played %d game and is cashing out with %d chips!\n", PlayerName, Games_Played, CurrentChips);
printf(" |---> Games won: %d\n", Games_Won);
printf(" |---> Games lost: %d\n", Games_Lost);
printf("Thanks for playing, come again to test that luck of yours %s.\n", PlayerName);
}
else
{
printf("%s played %d games and is cashing out with %d chips!\n", PlayerName, Games_Played, CurrentChips);
printf(" |---> Games won: %d\n", Games_Won);
printf(" |---> Games lost: %d\n", Games_Lost);
printf("\nThanks for playing, come again to test that luck of yours %s!\n", PlayerName);
}
return 0;
}
void display_details(void)
{
printf("File :.... assignment.c\n");
printf("Author :.... \n");
printf("Stud ID :.... \n");
printf("Email ID :.... \n");
printf("This is my own work as defined by the \n");
printf("University's Academic Misconduct Policy.\n");
}
int throws_die(void)
{
return 1 + rand() % 6;
srand is defined more or less like this:
void srand(unsigned int seed);
time is defined more or less like this:
__int64 time(__int64 *t);
Thus you pass an __int64 (64 bits) into an unsigned int (32 bits) parameter, which is not possible without potential trunctation. That's what the warning message is telling you.
So I am making a Craps game in my C class and am having trouble with a particular point. If a user rolls a 4, 5, 6, 8, 9 or 10 that is considered a point. If the user rolls a 7 after rolling a point they lose. My problem is if a user rolls a point, and then they roll again and the sum is equal to their point they win. My program works if they roll a 7 after their point, but not if they roll sum of their point again.
Sorry I know the question is confusing.
case 1: printf("Enter your name here: ");
scanf("%s", name);
for(j = 0; j < i; j++){
if(strcmp(name, pl[j].players)==0){
set = 1;
printf("* * * * * * * * * *\n");
printf("Press ENTER to roll the dice");
getchar();
getchar();
dice = (rand()%(6-1+1)+1);
dice1 = (rand()%(6-1+1)+1);
sum = dice + dice1;
printf("\nThe values of the dice are %d and %d whose sum is %d\n", dice, dice1, sum);
if(sum == 7 || sum == 11)
{
win++;
pl[j].wincount = win;
pl[j].balance = pl[j].balance + 10;
printf("\nYou win the game. \nYour balance is now: %d\n", pl[j].balance);
break;
}
else if((sum == 2) || (sum == 3) || (sum == 12))
{
lose++;
pl[j].balance = pl[j].balance-1;
printf("You lose :(\nYou balance is now: %d\n", pl[j].balance);
dice = (rand()%(6-1+1)+1);
dice1 = (rand()%(6-1+1)+1);
sum = dice + dice1;
break;
}
else
{
do
{
printf("\nYou rolled a 'point' you must now roll again.\n");
printf("* * * * * * * * * *\n");
printf("Press ENTER to roll the dice again");
getchar();
getchar();
dice = (rand() % (6 - 1 + 1) + 1);
dice1 = (rand() % (6 - 1 + 1) + 1);
sum = dice + dice1;
printf("\nThe values of the dices are %d and %d whose sum is %d\n", dice, dice1, sum);
}while((sum != 7) && (sum != point));
if(sum == 7)
{
lose++;
pl[j].balance = pl[j].balance - 1;
printf("You lose :(\nYou balance is now: %d\n", pl[j].balance);
}
else if(sum == point)
{
win++;
pl[j].wincount = win;
pl[j].balance = pl[j].balance + 10;
printf("\nYou won the game, you rolled your point \nYour balance is now: %d\n", pl[j].balance);
}
}
}
}
Well I have been assigned to do the prime factorisation for composite numbers, but the problem is I have hard-coded it till prime numbers:2,3,5,7,11,13,19 and I want to make it general.
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void prime(int flag,int num);
int main()
{
int num, flag, i, div;
printf("Enter your number: ");
scanf("%d", &num);
flag = 1;
prime(flag, num);
printf("Press any key to exit.");
getchar();
return 0;
}
void prime(int flag, int num)
{
void factor(int num, int i);
int sq, i, square;
sq = abs(sqrt(num));
if (num == 2)
flag = 1;
else
for (i = 2; i <= sq; i++)
{
if (num % i == 0)
{
flag = 0;
break;
}
else
flag = 1;
}
if (flag == 1)
printf("\n%d is a prime number", num);
else
{
printf("\n%d is not a prime number\n", num);
factor(num, i);
}
}
void factor(int num, int i)
{
for (i = 2; i <= num; i++)
{
again:
if(num % i == 0)
{
num = num / i;
printf("%d x", i);
if (num != (2||3||5||7||11||17||19))
goto again;
}
}
printf("1\n\n");
}
P.S.:Try to make it as simpler as possible.
The problem is after dividing it with smallest prime. i.e. 2 the next step should be check the number whether it is a prime or not. If not, then factorise it but I dont know how to do it.
Plz help.
Thx in advance.
#include <stdio.h>
void factor(int num);
int main(void){
int num;
printf("Enter positive number(more than 1): ");
if(1 != scanf("%d", &num) || num < 2){
printf("invalid input!\n");
return -1;
}
scanf("%*[^\n]");scanf("%*c");//clear upto line end
factor(num);
printf("Press any key to exit...");
getchar();
return 0;
}
void factor(int num){
int i, flag = 0;
if(num == 2){
printf("\n%d is a prime number\n", num);
return ;
}
while(!(num & 1)){
if(!flag)
printf("\n%d is not a prime number\n", num);
flag = 1;
printf("2 x ");
num >>= 1;
}
for (i = 3; i*i <= num; i += 2){
while(num % i == 0){
if(!flag)
printf("\n%d is not a prime number\n", num);
flag = 1;
printf("%d x ", i);
num /= i;
}
}
if(!flag)
printf("\n%d is a prime number\n", num);
else if(num != 1)
printf("%d x 1\n\n", num);
else
printf("1\n\n");
}
Replace line,
if (num!=2&& num!=3 && num!=5 && num!=7 && num!=11 && num!=17 && num!=19)
instead of,
if (num!=2||3||5||7||11||17||19)
In function factor, first try dividing by 2 repeatedly, then try every odd number while said odd number squared is less or equal to num. This simple method is a bit redundant as you try and divide by composite numbers, but since you will already have removed all smaller prime factors, num will not be divisible by such composite numbers. Iterating while i * i <= num will stop much earlier than with your current i <= num test.
Try and write code to implement the above algorithm and post it as an edit.