所以我对打印输出的顺序有问题。应该是“你有折扣券吗?”那么“是成人票还是儿童票打折?”然后基于该回答或者错误代码或者继续到收据。只有当用户在“您有折扣优惠券吗?”中有一个Y答案时,折扣才会弹出。部分。但是我不能用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时不打印错误消息(这是为折扣声明的),并且仅在任何其他情况下打印。
发布于 2019-09-19 07:35:46
如果你缩进你的代码,它更容易阅读。看起来你错过了几个It和elses。现在看起来是这样的:
if (haveDiscount == "Y")
{
// ask next question
}
if (haveDiscount == "N")
{
// print new line
}
else
{
// print error
}这意味着无论他们是否有折扣,它都会打印错误。如果haveDiscount不等于"N“,它将打印错误-如果他们在第一个问题中回答"Y”,则总是正确的。你可能想要更多像这样的东西:
if (haveDiscount == "Y")
{
// ask next question
if (discountType == "C" || discountType == "A")
{
// do something
}
else
{
// print error
}
}
else
{
// print new line
} 发布于 2019-09-19 08:24:51
要在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之后的某个位置。
https://stackoverflow.com/questions/58001853
复制相似问题