关于C语言的if语句 不知道哪里出错了 麻烦懂的人近来帮忙看一下

来源:百度知道 编辑:UC知道 时间:2024/05/15 03:34:20
#include <stdio.h>

void main()
{
double unit_price = 5.0;
long quantity = 0L;
double discount = 0.0;

printf("\nEnter the number that you want to buy:");
scanf("%ld",&quantity);

if(quantity > 30 & quantity < 50)
discount = 0.1;

printf("\nThe price for %ld is $%.2lf.",quantity,unit_price * quantity *(1.0 - discount));

if(quantity > 50)
discount = 0.15;

printf("\nThe price for %ld is $%.2lf.",quantity,unit_price * quantity *(1.0 - discount));

if(quantity > 0 & quantity < 30)
discount = 0.0;

printf("\nThe price for %ld is $%.2lf.",quantity,unit_price * quantity *(1.0 - discount));
getch();

}

我不明白为什么 不管输入哪种条件都会得到3个输出呢?麻烦懂的人看一下哪里出错了。
上面的程序if中的逻辑运算符忘打了个& 改过来一样还是不行
i

if(quantity > 30 & quantity < 50)
discount = 0.1;
这一句告诉你:if条件为真时执行discount=0.1;这句。所以printf("\nThe price for %ld is $%.2lf.",quantity,unit_price * quantity *(1.0 - discount));这一句要在if 条件中的话,要用一个大括号作为复合语句使用:
if(quantity > 30 & quantity < 50)
{
discount = 0.1;

printf("\nThe price for %ld is $%.2lf.",quantity,unit_price * quantity *(1.0 - discount));
}这样条件不为真时,不出显示这一句的。

没有中断退出

if 后面的句子要用 {} 括上。

#include <stdio.h>

void main()
{
double unit_price = 5.0;
long quantity = 0L;
double discount = 0.0;

printf("\nEnter the number that you want to buy:");
scanf("%ld",&quantity);

if(quantity > 30 & quantity < 50){
discount = 0.1;

printf("\nThe price for %ld is $%.2lf.",quantity,unit_price * quantity *(1.0 - discount));
}
if(quantity > 50){
discount = 0.15;