问题描述
- 这个c程序如果输入20的话,是不是只执行最后一个else后面的语句???
-
// Exercise 3.3 Calculate a discounted price// I interpreted this exercise as implying that the 10% applies to items 31 to 50
// and the 15% applies to items in excess of 50.
// That is, you don't get 15% discount on the whole price when you order 51 items.// There is more than one way of doing this so different is not necessarily wrong.
#include
int main(void)
{
const int level1 = 30; // Quantity over this level are at discount1
const int level2 = 50; // Quantity over this level are at discount2
const double discount1 = 0.10; // 10% discount
const double discount2 = 0.15; // 15% discount
const double unit_price = 5.0; // Basic unit price
int quantity = 0;
int qty_full_price = 0; // 0 to 30 at full price
int qty_level1 = 0; // 31 to 50 at level1 price
int qty_level2 = 0; // Over 50 at level2 price
printf("Enter the quantity that you require: ");
scanf("%d", &quantity);if(quantity > 50) // Quantity over 50
{
qty_full_price = level1;
qty_level1 = level2 - level1;
qty_level2 = quantity - level2;
}
else if(quantity > 30) // Quantity is from 30 to 50
{
qty_full_price = level1;
qty_level1 = quantity - level1;
}
else
qty_full_price = quantity;printf("The total price for %d items is $%.2lfn", quantity,
unit_price*(qty_full_price + (1.0 - discount1)*qty_level1 + (1.0 - discount2)*qty_level2));
return 0;
}
解决方案
是的,小于等于30的数都走最后一个else分支。也就是qty_full_price = quantity;这条语句。再后面的语句是公共的,不管哪个分支最后都会执行
解决方案二:
你最后一个else最好加一个花括号将执行的程序包括起来,这样你自己看着也方便简单些。
是的执行最后一个else,但是你的判断语句好像有问题,
解决方案三:
对,只执行最后一个。if...else...排他的
解决方案四:
但是这样程序就算不对,我用电脑输入20最后结果是100.但是我用笔算怎么也算不出100啊,我算出0了。。。。你算算看
解决方案五:
你觉得是
else if (...) { }
其实是
else
{
if (...) { }
}
因为是单条语句,else后面的块括号不用写。另外你要明白,C++不管你的缩进的。
好比
if (xxx)
aaa;
bbb;
ccc;
bbb总是执行。
解决方案六:
qty_full_price = quantity; -- qty_full_price = 数量20吗?
printf("The total price for %d items is $%.2lfn", quantity, -- 数量20
unit_price*(qty_full_price + (1.0 - discount1)*qty_level1 + (1.0 - discount2)*qty_level2));
-- qty_level1 = 0、qty_level2 =0、
那么unit_price*(qty_full_price + (1.0 - discount1)*qty_level1 + (1.0 - discount2)*qty_level2)) = 5.0 *(20+0 +0)=100,不是很正确吗?
查查输入20时,qty_level1 和 qty_level2有没有赋值?
解决方案七:
C语言风格
if ( xxx)
a;
b;
如条件成立 a 和 b都执行,不成立 b执行
if ( xxx)
a;
else
b;
c;
如条件成立 a c 执行,不成立 b c执行