C初学者在这里。我想知道如何让我的程序打印最后一行“您的总数是...”而不必输入另一个键。回答“多少个订单”问题后,如果没有输入其他键,代码中的最后一个printf语句将不会显示。希望您能有所帮助,谢谢。
#include <stdio.h>
int main() {
char choice;
int quantity;
int price;
printf("###############\n");
printf("##a Burger 50##\n");
printf("##b Hotdog 30##\n");
printf("##c Fries 20##\n\n");
printf("Hello, may I take your order please?\n\n");
printf("Please select the letter of your order.\n");
scanf("%c", &choice);
if (choice = 'a') {
printf("How many orders?\n");
scanf("%d\n", &quantity);
price = quantity * 50;
} else if (choice = 'b') {
printf("How many orders?\n");
scanf("%d\n", &quantity);
price = quantity * 30;
} else if (choice = 'c') {
printf("How many orders?\n");
scanf("%d\n", &quantity);
price = quantity * 20;
}
printf("Your total is %d, checkout in cashier.\n", price);
return 0;
}
答案 0 :(得分:3)
您的格式说明符存在问题
scanf("%d\n", &quantity);
格式字符串中的\n
导致scanf
等待,直到输入并在此之后输入其他字符为止。这就是为什么您必须输入其他键的原因。删除换行符,就可以输入值,而不必输入其他内容:
scanf("%d", &quantity);
此外,这并没有按照您的想法进行:
if (choice = 'a') {
...
} else if (choice = 'b') {
...
} else if (choice = 'c') {
在C =
中,赋值运算符而不是比较运算符。进行赋值时,表达式的值就是赋值。因此,第一个if
将'a'
分配给choice
,然后在布尔上下文中对该值求值。由于该值不为0,因此它将始终为true,因此您将永远不会输入其他两种情况之一。
为进行比较,您需要==
运算符:
if (choice == 'a') {
...
} else if (choice == 'b') {
...
} else if (choice == 'c') {
答案 1 :(得分:1)
从\n
中删除scanf("%d\n", &quantity);
,看起来像这样:
scanf("%d", &quantity);
答案 2 :(得分:0)
@dbush发布的答案涵盖了所有问题!但是,为了完整起见,下面是您的代码的编辑/更正/注释版本:
#include <stdio.h>
int main()
{
char choice;
int quantity;
int price;
printf("###############\n");
printf("##a Burger 50##\n");
printf("##b Hotdog 30##\n");
printf("##c Fries 20##\n\n");
printf("Hello, may I take your order please?\n\n");
printf("Please select the letter of your order.\n");
scanf("%c", &choice);
if (choice == 'a') { // NOTE: a == b COMPARES a with b whereas a = b ASSIGNS b to a.
printf("How many orders?\n");
scanf("%d", &quantity); // Don't expect scanf to read in a TERMINATING \n!
price = quantity * 50;
}
else if (choice == 'b') { // Vide supra!
printf("How many orders?\n");
scanf("%d", &quantity);
price = quantity * 30;
}
else if (choice == 'c') { // Vide supra supra!
printf("How many orders?\n");
scanf("%d", &quantity);
price = quantity * 20;
}
printf("Your total is %d, checkout in cashier.\n", price);
return 0;
}
这可以编译,运行和运行!