I am trying to make this short program work, but it gives a message of "expect expression" in the following part:
else
{
printf("program error!");
}
It looks like I am not using the if-elseif-else correctly. I've searched the web and found that the format is how I have it. Please help.
#include <stdio.h>
int main( )
{
double height, weight, bmi;
int bmievalcode;
while( 1 )
{
/* --> add code to input weight and height between here */
printf("Please enter weight in pounds and height in inches\n");
scanf("%lf %lf", &weight, &height);
bmi = (weight * 703.0)/(height * height);
bmievalcode = -1;
if (bmi < 18.5)
{
bmievalcode = 1;
}
else if (bmi >= 18.5 && bmi <25.0)
{
bmievalcode = 2;
}
else if (bmi >=25.0 && bmi < 30.0)
{
bmievalcode = 3;
}
else if (bmi >=30.0)
{
bmievalcode = 4;
}
/* bmievalcode:
* 1 = underweight
* 2 = normal
* 3 = overweight
* 4 = obese
*/
if (bmievalcode == 1 || bmievalcode == 2 || bmievalcode == 3 || bmievalcode == 4)
printf("bmi = %6.1lf, evaluation is ",bmi);
{
if (bmievalcode == 1)
printf("underweight");
else if (bmievalcode == 2)
printf("normal");
else if (bmievalcode == 3)
printf("overweight");
else if (bmievalcode == 4)
printf("obese");
printf(".\n");
}
else
{
printf("program error!");
}
}
return 0;
}
Your code is wrong here:
if (bmievalcode == 1 || bmievalcode == 2 || bmievalcode == 3 || bmievalcode == 4)
printf("bmi = %6.1lf, evaluation is ",bmi);
{
if (bmievalcode == 1)
printf("underweight");
else if (bmievalcode == 2)
printf("normal");
else if (bmievalcode == 3)
printf("overweight");
else if (bmievalcode == 4)
printf("obese");
printf(".\n");
}
else
{
printf("program error!");
}
The {} block isn't part of the if, it's separate. Then you have an else, but it's not directly after an if statement, which causes the error you see.
Move the line printf("bmi = %6.1lf, evaluation is ",bmi); to be after the opening {.
The statement directly after the if is what is affected by the condition. If this could compile, only that first printf would be conditionally executed. The curly-brace block would always run.
In this case, GCC is a little more helpful than Clang, telling you error: 'else' without a previous 'if'
Related
void main() {
int y = 0;
char password[30], username[40], total_items[10000], input_item,
ip11[] = "-IPhone 11\n", ipX[] = "-IPhone X\n";
char ap[] = "-AirPods\n", chrg[] = "-Charger\n";
char scrpro[] = "-Screen Protector\n", reset_str[] = " ";
int i = 0, total_amount = 0, auth = 4;
while (auth > 10)
;
{
printf("Enter Username:");
scanf("%s", &username);
fflush(stdin);
printf("Enter password:");
scanf("%s", &password);
fflush(stdin);
if ((strcmp(username, "admin") == 0) &&
(strcmp(password, "admin123") == 0)) {
auth += 7;
} else {
printf("Invalid password or username\n");
printf("%d tries left\n", auth);
auth -= 1;
}
}
while (y > 5) {
printf("Welcome,These are the items that we sell:\n");
printf("-----------------------------------------------\n");
printf("a. IPhone X - $1200 \nb. IPhone 11 - $1500\n");
printf(
"c. AirPods - $300 \nd. Charger - $15 \ne. Screen Protector - "
"$20\n");
printf("\n");
printf("To buy, key in the alphabet beside the item.\n");
printf("Please input 1 item at a time\n");
while (i < 10) {
printf("Enter item wanted(input 'z' to finish cart):");
scanf(" %c", &input_item);
if ((input_item == 'a') || (input_item == 'A')) {
total_amount += 1200;
strcat(total_items, ipX);
} else if ((input_item == 'b') || (input_item == 'B')) {
total_amount = total_amount + 1500;
strcat(total_items, ip11);
} else if ((input_item == 'c') || (input_item == 'C')) {
total_amount = total_amount + 300;
strcat(total_items, ap);
} else if ((input_item == 'd') || (input_item == 'D')) {
total_amount = total_amount + 15;
strcat(total_items, chrg);
} else if ((input_item == 'e') || (input_item == 'E')) {
total_amount = total_amount + 20;
strcat(total_items, scrpro);
} else if ((input_item == 'z') || (input_item == 'Z'))
i += 10;
else
printf("Invalid item, please input again\n");
}
printf("Your total is: $%d\n", total_amount);
printf("Your items are:\n%s\n", total_items);
printf("Please collect your receipt and head over to the counter\n");
printf("Thank you for coming to OneTop!\n");
printf("\n");
strcpy(total_items, reset_str);
}
}
I expected the code to proceed to the second while loop but the code instead just crashes.
Incorrect format specifier:
scanf("%s", &username);
username is a constant pointer to the first element of the array. There's no need to use the & operator with it.
Stray semicolon:
The statement:
while (auth > 10)
;
is equivalent to saying:
"While auth is greater than 10, do nothing."
It's dead code.
The block of code after the while loop will always execute, irregardless of the value of auth.
Even if you were to remove the semi-colon, the program would never enter the loop, as:
auth == 4
And the condition:
if (auth > 10)
is false.
Similarly, the second loop would never be entered, as:
y == 0
And the condition:
if (y > 5)
is false.
Flushing stdin:
fflush(stdin);
is undefined behaviour.
Once the abstract state machine reaches undefined behaviour, no further assumption about the continuation of the execution of the program can be made.
Aside:
Implementation-defined definition of main:
From C11:
The function called at program startup is named main. The
implementation declares no prototype for this function. It shall be
defined with a return type of int and with no parameters:
int main(void) { /* ... */ }
or with two parameters (referred to here as argc and argv, though any
names may be used, as they are local to the function in which they are
declared):
int main(int argc, char *argv[]) { /* ... */ }
or equivalent;10) or in some other implementation-defined manner.
Did you check your variables? Your first while loop while(auth > 10);, but auth = 4. Maybe you meant while(auth < 10);. Same for while (y > 5),, because y = 0
I'm trying to make a chomp game in c as a school assignment, but have been stuck at a silly IF - statement...
Basically, every time it runs (the CheckMove function), if I make a turn that isn't correct, it goes straight down to the else statement instead of returning the correct int... why??
I have removed lots of the code that isn't part of the problem. hope it is okay.. din't know if it is more appreciated to post the whole program instead...
Please help!
while(1)
{
PrintBoard();
player = (player == 2) ? 1 : 2;
while(1)
{
GetMove(player, move);
if (CheckMove(move) == 0) // if everything is fine, break the loop and change player
{
UpdateBoard(move);
break;
}
else if (CheckMove(move) == 1) //this never gets triggered
{
printf("\nAlready taken. Please try again! (row col): ");
continue;
}
else if (CheckMove(move) == 2) //this never gets triggered
{
printf("\nYou lost!\n");
return 0;
}
else if (CheckMove(move) == 3) //This ALWAYS gets triggered
{
printf("\nIllegal move. Try again! (row col): ");
continue;
}
}
}
}
void Initialize()... // initializes the board
void PrintBoard()... // prints the board
void GetMove(int player, int move[2])
{
printf("\nPlayer %d: your move! (row col): ", player);
for (int i = 0; i < 2; i++) scanf(" %d", &move[i]);
}
int CheckMove(int move[2])
{
int check = 99;
if ((move[0] >= 1 && move[0] < 5) && (move[1] >= 1 && move[1] <= 10))
{
move[0] -= 1;
move[1] -= 1;
// more checks
if (board[move[0]][move[1]] == 'Z')
{
check = 1;
}
else if(board[move[0]][move[1]] == 'X')
{
check = 2;
}
else
{
check = 0;
}
}
else { check = 3; } //as soon as I hit check 1 or 2, I end up here...
return check;
}
As a mandatory preface, I am new to C, and am likely simply missing something extremely obvious. I appreciate any and all time and effort taken to look over my silly problem.
I have a recursive function whose purpose is to print out a large "x" made of smaller x characters, where width is the length of each side of the x. For example, a width of "3" would have the following output:
Shape:
X X
X
X X
Returning.
Where "Returning." prints just before returning to main.
The following function does just this for a width of 1 and 3, but fails to do so with 5, 7, 9, etc.
void Recurse(int left, int right, int flag, int num){
int i;
if(((left && right) == num/2) && (flag == 0)){
for(i=0;i<num;i++){
if (i == (num/2) ){
printf("X");
}
else
printf(" ");
}
printf("\n");
flag = 1;
Recurse(left-1, right+1, flag, num);
}
else if(flag == 0){
for(i=0;i<num;i++){
if((i == left) || (i == right)){
printf("X");
}
else
printf(" ");
}
printf("\n");
Recurse(left+1, right-1, flag, num);
}
else if(flag == 1){
for(i=0;i<num;i++){
if((i == left) || (i == right)){
printf("X");
}
else
printf(" ");
}
printf("\n");
if (((left == 0) && (right == num-1)) && (flag == 1))
printf("\nReturning.\n");
return;
Recurse(left-1, right+1, flag, num);
}
}
The only thing I have in my main function is an initialization of width with some odd int, and a call to the function. I would like to get the code actually... printing correctly prior to cleaning up the logic a bit. Thank you for any help provided.
In
if(((left && right) == num/2) && (flag == 0)){
left && right is a boolean value, probably you wanted
if ((left == num/2) && (right == num/2) && (flag == 0)){
Below is a code I wrote for a dice game called cho han. To input your guess I've used number to represent the words 'odd' and 'even'. Since then I have tried to write it again, but to actually write odd or even in the scanf section, but can't get it to work. Any help would be appreciated :)
//cho-han
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
srand(time(NULL));
int x = (rand() % 6) + 1;
int y = (rand() % 6) + 1;
int result = 0;
int guess = 0;
printf("The values of two dice rolls will be added up. The aim is to guess whether that total number will be odd or even.\n");
printf("To guess odd, enter '1'. To guess even, enter '2'.\n\n");
printf("Please enter your guess for the combined total of the two dice rolls: ");
scanf_s("%d", &guess);
if (guess == 2)
{
printf("\nyour guess is even.\n");
}
if (guess == 1)
{
printf("\nyour guess is odd.\n");
}
if (guess > 2 || guess < 1)
{
printf("\nInvalid guess.\nYou lose!\n");
return (1);
}
printf("\ndice roll 1 = %d\n", x);
printf("dice roll 2 = %d\n", y);
result = x + y;
printf("\ncombined total of both rolls is %d", result);
if (result == 1 || result == 3 || result == 5 || result == 7 || result == 9 || result == 11)
{
printf("\ncombined total of both rolls is odd.\n");
}
else
{
printf("\ncombined total of both rolls is even.\n");
}
if (guess == 1 && result == 1 || guess == 1 && result == 3 || guess == 1 && result == 5 || guess == 1 && result == 7 || guess == 1 && result == 9 || guess == 1 && result == 11)
{
printf("\nYou win!\n");
}
else if (guess == 2 && result == 2 || guess == 2 && result == 4 || guess == 2 && result == 6 || guess == 2 && result == 8 || guess == 2 && result == 10 || guess == 2 && result == 12)
{
printf("\nYou win!\n");
}
else
{
printf("\nYou lose!\n");
}
return 0;
}
You should change scanf_s to scanf
The line if (result == 1 || result == 3 ... could be if (result % 2 == 1) {
You could use strcmp to solve your question
The following code could work:
//cho-han
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int main(void)
{
srand(time(NULL));
int x = (rand() % 6) + 1;
int y = (rand() % 6) + 1;
int result = 0;
int guess = 0;
char buf[10];
printf("The values of two dice rolls will be added up. The aim is to guess whether that total number will be odd or even.\n");
printf("To guess odd, enter 'odd'. To guess even, enter 'even'.\n\n");
printf("Please enter your guess for the combined total of the two dice rolls: ");
fgets(buf, sizeof buf, stdin);
if (strcmp(buf, "even\n") == 0) {
guess = 2;
printf("\nyour guess is even.\n");
} else if (strcmp(buf, "odd\n") == 0) {
guess = 1;
printf("\nyour guess is odd.\n");
} else {
printf("\nInvalid guess.\nYou lose!\n");
return 1;
}
printf("\ndice roll 1 = %d\n", x);
printf("dice roll 2 = %d\n", y);
printf("\ncombined total of both rolls is %d", x + y);
result = (x + y) % 2;
if (result == 1)
printf("\ncombined total of both rolls is odd.\n");
else
printf("\ncombined total of both rolls is even.\n");
if (guess == result)
printf("\nYou win!\n");
else
printf("\nYou lose!\n");
return 0;
}
You need to change your guess to char type and scanf to capture string.
char guess[256];
scanf("%s", guess);
And then the best way would be to call toupper() and compare with your text using strcmp().
Thank you to anyone who tries to help me with this!
So what should happen here is that if you run this, and you pick class choice 1,2 or 3, then when you go into the battle your attacks are different etc.
I'm making it so that you have to win rock paper scissors to be able to attack, so if the computer wins it attacks you.
For class choice 1, this works, however for the other two is doesn't and I'm lost as to why.
I'm very new to c so sorry if I'm missing something obvious!
For example if you pick class choice 3, guardian, and you win or lose the rock paper scissors game, nothing happens at all, where as it should let you attack or him attack
#include<stdio.h>
#include<string.h>
int i;
int playerschoice, compchoice;
main()
{
int i;
int choice1,choice2;
int class_choice,warrior,rogue,guardian;
int HoodMan_Health = 30;
int HoodMan_HealthCurrent;
int HoodManAtk = 25;
int HoodManDef = 15;
int RogueAtk = 100;
int RogueDef = 10;
int WarriorAtk = 50;
int WarriorDef = 50;
int GuardianAtk = 10;
int GuardianDef = 100;
int health = 100;
int currenthealth;
int difficulty;
int level;
printf("\n1.Rogue [100atck 10def]\n\n2.Warrior [50atck 50def]\n\n3.Guardian [10atck 100def]\n");
printf("\nYour choice?\t");
scanf("%i",&class_choice);
if (class_choice == 1 || class_choice == 2 ||class_choice == 3)
{
printf("\nLets play...\n\n");
system ("PAUSE");
}
else
{
printf("\nThat was not a choice\n");
return(0);
}
while ( (currenthealth>0)&&(HoodMan_Health>0) ) // while both healths are above zero do this battle
rockpaperscissors();
{
if (((playerschoice == 1)&&(compchoice == 3)) || ((playerschoice == 2)&&(compchoice == 1)) || ((playerschoice == 3)&&(compchoice == 1)))
{
printf("You attack the hooded man\n");
if (class_choice == 1)
{
HoodMan_Health=HoodMan_Health-(RogueAtk*0.5+HoodManDef*0.25);
printf("The Hooded Man's health is now %i\n\n",HoodMan_Health);
}
else if (class_choice == 2)
{
HoodMan_Health=HoodMan_Health-(WarriorAtk*0.5+HoodManDef*0.25);
printf("The Hooded Man's health is now %i\n\n",HoodMan_Health);
}
else if (class_choice == 3)
{
HoodMan_Health=HoodMan_Health-(GuardianAtk*0.5+HoodManDef*0.25);
printf("The Hooded Man's health is now %i\n\n",HoodMan_Health);
}
}
else if (((playerschoice == 3)&&(compchoice == 1)) || ((playerschoice == 1)&&(compchoice == 2)) || ((playerschoice == 1)&&(compchoice == 3)))
{
printf("The Hooded Man attacks you\n");
if (class_choice == 1)
{
currenthealth=currenthealth-(HoodManAtk+RogueDef*0.5);
printf("Your health is now %i\n\n\n",currenthealth);
}
else if (class_choice == 2)
{
currenthealth=currenthealth-(HoodManAtk+WarriorDef*0.5);
printf("Your health is now %i\n\n\n",currenthealth);
}
else if (class_choice == 3)
{
currenthealth=currenthealth-(HoodManAtk+GuardianDef*0.5);
printf("Your health is now %i\n\n\n",currenthealth);
}
}
}
if (currenthealth<0)
{
printf("You died\n");
return (0);
}
else
{
printf("You killed the hooded man\n");
}
}
void rockpaperscissors()
{
printf("Enter 1 for Rock, 2 for Paper and 3 for Scissors\n");
scanf("%i",&playerschoice);
if ( playerschoice == 1 )
{
printf("You are going with: Rock...\n");
}
else if ( playerschoice == 2 )
{
printf("You are going with: Paper...\n");
}
else if ( playerschoice == 3 )
{
printf("You are going with: Scissors...\n");
}
else if ( playerschoice != 1||2||3)
{
printf("that was not a choice");
return(0);
}
// initialize random seed: //
srand (time(NULL));
// set compchoice to random number from 1 to 3 //
compchoice=rand() %3+1;
if (compchoice == 1)
{
printf("\nThe computer is going with: Rock...\n\n");
}
else if (compchoice == 2)
{
printf("\nThe computer is going with: Paper...\n\n");
}
else if (compchoice == 3)
{
printf("\nThe computer is going with: Scissors...\n\n");
}
{
if (((playerschoice == 1)&&(compchoice == 3)) || ((playerschoice == 2)&&(compchoice == 1)) || ((playerschoice == 3)&&(compchoice == 1)))
{
printf("you win\n");
}
else if (((playerschoice == 3)&&(compchoice == 1)) || ((playerschoice == 1)&&(compchoice == 2)) || ((playerschoice == 1)&&(compchoice == 3)))
{
printf("you lose\n");
}
else if (((playerschoice == 1)&&(compchoice == 1)) || ((playerschoice == 2)&&(compchoice == 2)) || ((playerschoice == 3)&&(compchoice == 3)))
{
printf("it's a draw\n");
}
}
}
Here are the chief errors in your program:
To use: system("pause"); you should include <windows.h>
To use: time(NULL) you should include <time.h>
string.h isn't really required in your program.
You haven't initialized currenthealth which can lead to unpredictable outcome.
You have made variables like health and HoodMan_HealthCurrent but are not using them.
Call to rockpaperscissors() should be inside the while block.
Putting it outside makes the loop infinite and the code in the block never gets executed!
If you want to use floating point arithmetic like HoodManDef*0.25 you should declare it as float or else it will be rounded off.
The condition else if ( playerschoice != 1||2||3) is wrong(always true) and redundant(The above three conditions imply that playerschoice will not be 1,2 or 3 ).
A simple else will suffice.
rockpaperscissors() is a void function.You cannot return(0);. Use a simple return; instead.
You don't have to use srand() every time you call the function.You can simply use it at the start of program or when each game starts(if you plan to make it re playable without restarting) .
Some Problems with the game:
You are adding character's defense to opponent's attack! i.e the more defense i have , the more powerful my opponent will become . You should subtract instead.
Defense of warrior and Guardian is so much that their health won't decrease even if attacked by the hoodman.