当用户输入的值等于或小于零以正确嵌套时,我无法获取错误消息。我不确定它应该去哪里,或者我是否需要完全做其他事情。任何帮助,将不胜感激。以下是我的代码。
说明: “某软件公司销售零售价为 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;
}
最佳答案
您的代码可以这样修复:
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";
应该做一些其他的小改动以使代码看起来更好 - 这取决于您
关于c++ - 无法正确嵌套我的错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40060279/