所以我有这个代码,但我遗漏了一些东西,我似乎无法得到它。这一点是提示用户进行选择。他们挑选他们想要订购的食物,并告诉他们添加了。当用户点击0时,程序结束时说出他们选择的所有项目的总数。出于某种原因,当我到达终点时,它只是说明添加的最后一项的总和。关于如何解决这个问题以便总计加起来的任何想法?
#include<stdio.h>
#define SALES_TAX .06
int selection;
double total;
double amount;
int i;
double getPrice(int selection);
void printOptionName(int selection);
void printMenu();
double getPrice(int selection){
if (selection == 1){
amount = 5.99;
} else if (selection == 2){
amount = 6.99;
} else if (selection == 3){
amount = 7.99;
} else if (selection == 4){
amount = 10.50;
} else if (selection == 5){
amount = 3.50;
}
}
void printOptionName(int selection){
if (selection == 0){
printf("\nYour total is: ");
} else if (selection == 1){
printf("\nAdded a Small Pizza\n\n");
} else if (selection == 2){
printf("\nAdded a Medium Pizza\n\n");
} else if (selection == 3){
printf("\nAdded a Large Pizza\n\n");
} else if (selection == 4){
printf("\nAdded an order of Wings\n\n");
} else if (selection == 5){
printf("\nAdded a Drink\n\n");
} else
printf("Not a valid selection. Please select one of the following options: \n");
}
void printMenu(){
printf("0. (Complete Order)\n");
printf("1. Small Pizza ****** 5.99\n");
printf("2. Medium Pizza ****** 6.99\n");
printf("3. Large Pizza ****** 7.99\n");
printf("4. Wings ****** 10.50\n");
printf("5. Drink ****** 3.50\n");
printf("Enter the Number of your selection: \n");
}
int main(){
printMenu();
scanf("%d", &selection);
printOptionName(selection);
getPrice(selection);
while (selection != 0){
printMenu();
scanf("%d", &selection);
printOptionName(selection);
getPrice(selection);
}
for (i = 0; i <= selection; i++){
total = total + amount;
}
printf("%lf\n", total);
return 0;
}
答案 0 :(得分:1)
全局变量不是一个好方法。请注意,您未在selection
中使用printmenu()
,例如;您可能希望将必要的数据作为参数传递给函数。此外,您似乎在通过值传递的函数中通过引用传递。请注意,如果您的程序转到else
中的printOptionName()
语句,或getPrice()
中的选项仍为零,则您的程序不会停止...