-1

编写一个程序,提示用户输入文章的价格和定价代码。您的程序应计算新的折扣价并验证输入。

这段代码中的所有内容都是正确的,但是当我运行编译器时,我输入 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);
}
}
4

1 回答 1

0

您遇到的问题是scanf()只从输入缓冲区中抓取一个字符。这会很好,除了输入缓冲区中仍然有一个换行符是由于在您输入后点击“输入”而导致的。您需要在使用后清除输入缓冲区,scanf()如下所示:

scanf("%c", &code);
while(code == '\n'){scanf("%c", &code);}

或刷新缓冲区

于 2013-08-19T08:47:35.863 回答