所以我有这段代码,但我遗漏了一些东西,而且我似乎不太明白它。这样做的目的是提示用户进行选择。他们选择想要点的食物,它会告诉他们食物已添加。当用户点击 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;
}
最佳答案
全局变量并不是一个好方法。请注意,例如,您没有在 printmenu()
中使用 selection
;您可能希望将必要的数据作为参数传递给函数。另外,您似乎在按值传递的函数中按引用传递。请注意,如果您的程序转到 printOptionName()
或 getPrice()
中的 else
语句,则它不会停止,选择仍然会为零...
关于C 编程帮助 - 将值相加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28799257/