Reputation: 1
I am writing a program that is needing input validation saying that if the units are less than or equal to 0 the program won't run, but I keep getting the string with the total included but I am not trying to run that if the value is 0.
//Write a program that asks for the numbers of units sold and computes the total cost of purchase
//Make sure to use input validation that the number of units is greater than 0
#include <iostream>
using namespace std;
int main ()
{
double discount, discountTotal, units, total;
double package = 99;
cout << "What is the number of units sold? ";
cin >> units;
if(units <=0){
cout << "Units must be greater than 0" << endl;
}
if(units > 0 && units < 10)
discount = .00;
else if(units >=10 && units <= 19)
discount = .20;
else if(units >=20 && units <= 49)
discount = .30;
else if(units >=50 && units <= 99)
discount = .40;
else if(units >=100, .50)
discount = .50;
discountTotal = package * discount;
total = package - discountTotal;
cout << "Your total is: " << total << endl;
return 0;
}
Upvotes: 0
Views: 346
Reputation: 162
Mmm... I think that would be better:
#include <iostream>
using namespace std;
int main ()
{
double discount, discountTotal, units, total;
double package = 99;
cout << "What is the number of units sold? ";
cin >> units;
if(units <=0)
{
cout << "Units must be greater than 0" << endl;
}
else
{
if(units > 0 && units < 10)
discount = .00;
else if(units >=10 && units <= 19)
discount = .20;
else if(units >=20 && units <= 49)
discount = .30;
else if(units >=50 && units <= 99)
discount = .40;
else if(units >=100, .50)
discount = .50;
discountTotal = package * discount;
total = package - discountTotal;
cout << "Your total is: " << total << endl;
}
return 0;
}
And you were outputting the total no matter what the user enter... Hope it help!
Upvotes: 0
Reputation: 17999
You can return
immediately if the input is not correct:
if(units <=0){
cout << "Units must be greater than 0" << endl;
return -1; // if the input 0 or negative, the program will end here
}
Without that, the following code is always executed:
// ...
discountTotal = package * discount;
total = package - discountTotal;
cout << "Your total is: " << total << endl;
// ...
Related: What should main() return in C and C++?
Upvotes: 2