所以我在打印所有内容时遇到了问题。应该是“您有优惠券吗?”然后,“是成人票还是儿童票的折扣?”然后根据答案输入错误代码或进入收据。仅当用户在“您有折扣券吗?”中回答“是”时,折扣才弹出。部分。但是我无法使其与if和else语句一起使用。
起初,我尝试将所有的if和else语句放在一起,但打印顺序不正确。因此,现在我尝试在中间插入收据,但这使if语句的操作混乱,并且收据显示不正确。无论我输入C还是A(稍后都会声明这两个字符,并且不应该提示打印错误消息),都会打印错误消息。折扣仍然适用,但错误消息不应打印。
cout<< "\nDo you have a discount coupon (Y for yes)? ";
cin>> haveDiscount;
if (haveDiscount == "Y")
{
cout<< "\nIs the discount for an adult or child's ticket (A for adult, C for child)? ";
cin>> discountType;
}
if (haveDiscount == "N")
{
cout<< endl;
}
else
{
cout<< "\nError: ";
cout<< discountType;
cout<<" is not a valid discount type. No discount will be applied.";
}
cout<< "\n\n************************************" << endl;
cout<< right << setw(22) << "Theater Sale";
cout<< "\n************************************";
cout<< "\n\nNumber of adult tickets: " << setw(11) << adultTickets;
cout<< "\nNumber of child tickets: " << setw(11) << childTickets << endl;
if (discountType == "A")
{
coupon = 11.25;
cout<< "\nDiscount: " << setw(26) << coupon << endl;
}
else
{
if (discountType == "C")
{
coupon = 4.50;
cout<< "\nDiscount: " << setw(26) << coupon << endl;
}
}
total = (adultPrice * adultTickets) + (childPrice * childTickets) - coupon;
cout<< "\nTotal purchase: " << setw(20) << total;
我需要输入C或A(声明为折扣)时不打印错误消息,并且仅在其他情况下打印。
答案 0 :(得分:0)
如果您缩进代码,则阅读起来会容易得多。看来您缺少了一些假设。 现在看起来像这样:
if (haveDiscount == "Y")
{
// ask next question
}
if (haveDiscount == "N")
{
// print new line
}
else
{
// print error
}
这意味着无论他们有什么折扣,它都将打印错误。如果haveDiscount不等于“ N”,则会显示错误-如果他们对第一个问题回答“ Y”,则该错误将始终为true。 您可能想要更多类似这样的东西:
if (haveDiscount == "Y")
{
// ask next question
if (discountType == "C" || discountType == "A")
{
// do something
}
else
{
// print error
}
}
else
{
// print new line
}
答案 1 :(得分:0)
在discountType
不是C或A的情况下打印错误看起来像
if (discountType == "A")
{
coupon = 11.25; cout<< "\nDiscount: " << setw(26) << coupon << endl;
}
else if (discountType == "C")
{
coupon = 4.50; cout<< "\nDiscount: " << setw(26) << coupon << endl;
}
else
{
cout<< "\nError: ";
cout<< discountType;
cout<<" is not a valid discount type. No discount will be applied."; }
}
如果您想在收据前打印错误,则可以
if (discountType != "C" || discountType != "A")
{
// Error message
}
设置了discountType
之后的某处。