我无法在用户输入的值等于或小于零时获取错误消息以正确嵌套。我不确定它应该去哪里,或者我是否需要完全做其他事情。任何帮助,将不胜感激。下面是我的代码。
说明: “一家软件公司出售零售价为99美元的套餐。数量折扣根据以下条件给出:”10-19 = 20%折扣,20-49 = 30%折扣,50-99 = 40%折扣,100 + = 50 %折扣。 编写一个程序,询问购买的单位数量,并计算购买的总成本。 输入验证:确定程序应如何处理小于0的输入。
#include <iostream>
#include <iomanip> // needed for setprecision
#include <stdio.h>
using namespace std; // need to use cout, cin, etc.
int main()
{
double quantity, package = 99.00, initialPrice, discPrice, discount, calcDiscount, percent; // using double here because future multiplication by .2
cout << "This program will calculate how much of a discount you may receive,\nbased on how many software packages you buy.\n\n";
cout << "How many software packages do you intend to purchase?\n\n";
cin >> quantity;
{
if (quantity <= 0)
cout << "\nThat is not an acceptable amount. Please re-run the program with a amount greater than zero.\n\n";
}
if ( quantity >= 10 && quantity <= 19)
discount = 0.2, percent = 20;
else if ( quantity >= 20 && quantity <= 49)
discount = 0.3, percent = 30;
else if ( quantity >= 50 && quantity <= 99)
discount = 0.4, percent = 40;
else if ( quantity >= 100 )
discount = 0.5, percent = 50;
else if (quantity <10 && quantity >=1)
discount = 0, percent = 0;
{
initialPrice = package * quantity;
calcDiscount = (discount * package * quantity);
discPrice = initialPrice - calcDiscount;
cout << "\nThe total price for " << quantity << " software packages, minus a " << percent << "% discount of $";
cout << fixed << showpoint << setprecision(2) << calcDiscount << ",";
cout << " is $" << fixed << showpoint << setprecision(2) << discPrice << ".\n\n";
}
return 0;
}
答案 0 :(得分:1)
您的代码可以像这样修复:
if (quantity <= 0)
{
cout << "\nThat is not an acceptable amount. Please re-run the program with a amount greater than zero.\n\n";
return -1;
}
else if ( quantity < 10)
discount = 0, percent = 0;
else if ( quantity < 20)
discount = 0.2, percent = 20;
else if ( quantity < 50)
discount = 0.3, percent = 30;
else if ( quantity < 100)
discount = 0.4, percent = 40;
else discount = 0.5, percent = 50;
initialPrice = package * quantity;
calcDiscount = (discount * package * quantity);
discPrice = initialPrice - calcDiscount;
cout << "\nThe total price for " << quantity << " software packages, minus a " << percent << "% discount of $";
cout << fixed << showpoint << setprecision(2) << calcDiscount << ",";
cout << " is $" << fixed << showpoint << setprecision(2) << discPrice << ".\n\n";
应该进行一些其他细微的更改,以使代码看起来更好 - 它在你身上