目前正在使用Clion处理家庭作业问题。我相信我正确地使用了if语句,double和char语句,但似乎并没有给我我想要的结果。问题问:
我试图将括号移动。我已经将.90声明为集合变量,并尝试将其相乘,但仍然始终能得到相同的答案。我认为这与我的if-statemets有关。
using namespace std;
int main() {
double price1, price2, taxRate, fullSubtotal;
char clubCard;
double basePrice, cardPrice, finalPrice;
// ...
cout<<"Enter price of first item: ";
cin>>price1;
cout<<"Enter price of second item: ";
cin>>price2;
cout<<"Does customer have a club card? (Y/N): ";
cin>>clubCard;
cout<<"Enter tax rate, e.g. 5.5 for 5.5% tax: ";
cin>>taxRate;
fullSubtotal = price1 + price2;
taxRate /= 100;
taxRate += 1;
if (price1 > price2) {
price2 /= 2.00;
basePrice = price1 + price2;
if (clubCard == 'y' || clubCard == 'Y') {
cardPrice = basePrice * .90;
finalPrice = taxRate * cardPrice;
}
else (clubCard == 'n' || clubCard == 'N'); {
cardPrice = basePrice;
finalPrice = taxRate * cardPrice;
}
}
else {
price1 /= 2.00;
basePrice = price1 + price2;
if ((clubCard == 'y') || (clubCard == 'Y')) {
cardPrice = basePrice * .90;
finalPrice = taxRate * cardPrice;
}
else ((clubCard == 'n') || (clubCard == 'N')); {
cardPrice = basePrice;
finalPrice = taxRate * cardPrice;
}
}
cout<<"Base price: "<<fullSubtotal<<endl;
cout<<"Price after discounts: "<<cardPrice<<endl;
cout<<"Total price: "<<finalPrice<<endl;
return 0;
}
每次我输入每个价格(10和20)的值时,它都会给我正确的fullSubtotal,但是当我为该路线(如果声明)寻找相应的cardPrice时,它会给我25。总价格(包括税) )为27.0625。我期望输出为cardprice:22.5,最终价格:24.35625
最佳答案
您的错误在于内部的else子句。
else子句没有条件,因此(clubCard == 'n' || clubCard == 'N');
是无用的,但仍然是正确的c++。它评估为 bool(boolean) 值,然后将其丢弃。问题在于,此之后的块始终被执行,因为它不再具有任何条件。
使用else if
并删除分号,或者仅删除整个条件和分号:
...
if (clubCard == 'y' || clubCard == 'Y') {
cardPrice = basePrice * .90;
finalPrice = taxRate * cardPrice;
}
else {
cardPrice = basePrice;
finalPrice = taxRate * cardPrice;
}
....
关于c++ - 乘以十进制不会给我十进制答案以反馈到我的变量中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57283650/