编写一个程序,提示用户输入商品价格和定价代码。您的程序应计算新的折扣价并验证输入。
这个代码中的所有内容都是正确的,但是当我运行编译器时,我输入100的价格,但是那个游标没有停在定价代码上,而且我无法输入我想要的定价代码?为什么游行不会在“定价代码”之后停止?
#include <stdio.h>
main()
{
float price, discp;
char code;
printf("Price Calculator");
printf("\n\n========================");
printf("\n\nEnter the price: $ ");
scanf("%f", &price);
printf("\n\nEnter the pricing code: ");
scanf("%c", &code);
if ((code=='C')||(code=='c'))
{
discp=price-0.3*price;
printf("\n\n\nNew discounted price is $%.2f\n\n\n\n\n\n\n", discp);
}
if ((code=='A')||(code=='a'))
{
discp=price-0.5*price;
printf("\n\n\nNew discounted price is $%.2f\n\n\n\n\n\n\n", discp);
}
if ((code=='B')||(code=='b'))
{
discp=price-0.4*price;
printf("\n\n\nNew discounted price is $%.2f\n\n\n\n\n\n\n", discp);
}
if ((code=='D')||(code=='d'))
{
discp=price-0.1*price;
printf("\n\n\nNew discounted price is $%.2f\n\n\n\n\n\n\n", discp);
}
if ((code=='E')||(code=='e'))
{
discp=price;
printf("\n\n\nNew discounted price is $%.2f\n\n\n\n\n\n\n", discp);
}
else
{
printf("\n\n\nInvalid Pricing Code\n\n\n\n\n\n\n", discp);
}
}
答案 0 :(得分:0)
您遇到的问题是scanf()
只从输入缓冲区中抓取一个字符。这样就可以了,除了输入缓冲区中仍然有一个新行,这是因为输入后点击'enter'而导致的。你需要在使用scanf()
之后清除输入缓冲区:
DO
scanf("%c", &code);
while(code == '\n'){scanf("%c", &code);}
或刷新缓冲区