In you code you have duplicated multiple times:
...
if(choice == 1){
menu();
break;
} ...
...
So when you choose choice = 1
then menu()
get's displayed, and then the code breaks out of foods()
. I think you meant to do the foods section again:
...
if(choice == 1){
menu();
foods();
break;
} ...
...
Yet another problem in your code is the %c
scanf modifier. It will not eat up leading whitespaces, so it will read a newline (inputted on the last scanf). Use a leading space " %c"
to tell scanf to read up leading whitespaces and ignore the leading newline, in scanf(" %c", &food);
- Indent your code.
- Don't duplicate statements. The whole
scanf(... &choice); if (choice == 1) ... else if (choice == 2)
could be placed outside the while
switch not beeing duplicated 4 times.
- Nesting functions using recursive calls can make your stack run out. Better just use a while loop.
- Try not to use global variables. They are misleading and lead to maintainable code.
A slightly modified version of you code with a bit of indententation, added a do ... while
loop and removed global variables and code duplication, may look like this:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
char menu(void);
float foods(char food);
void main()
{
clrscr();
float grandtotal = 0;
int choice = 0;
do {
// print menu and choose the food
char food = menu();
// choose food quantity and get it's price
float total = foods(food);
// print the total price
grandtotal = grandtotal + total;
printf("
Total Price is: %0.2f", grandtotal);
// do you want to continue?
printf("
Do you want to order more? [1] Yes [2] No:");
if (scanf("%d", &choice) != 1) {
perror("scanf error");
abort();
}
// continue until choice is equal to 1
} while (choice != 1);
}
char menu(void)
{
char food;
printf("Please select food from the following:
");
printf(" B = Burger, F = French Fries, P = Pizza, S = Sandwiches
");
printf("Enter food:");
if (scanf(" %c", &food) != 1) {
perror("scanf error");
abort();
}
return food;
}
float foods(char food){
float price = 0;
switch (food) {
case 'B':
printf("You selected Burger!
");
price = 95.50;
break;
case 'F':
printf("You selected French Fries!
");
price = 47.75;
break;
case 'P':
printf("You selected French Pizza!
");
price = 105.00;
break;
case 'S':
printf("You selected Sandwiches
");
price = 75.50;
break;
default:
fprintf(stderr, "INVALID FOOD!
");
abort();
}
printf("Enter quantity:");
int quantity;
if (scanf("%d", &quantity) != 1) {
perror("scanf error");
abort();
}
return (float)price * (float)quantity;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…