C ++中的输入验证

时间:2015-09-21 16:55:46

标签: c++ validation if-statement

我正在编写一个需要输入验证的程序,如果单位小于或等于0,程序将无法运行,但我不断获取包含总数的字符串,但我不是试图运行如果值为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;
}

2 个答案:

答案 0 :(得分:2)

如果输入不正确,您可以立即return

if(units <=0){
    cout << "Units must be greater than 0" << endl;        
    return -1; // if the input 0 or negative, the program will end here
}

如果没有,以下代码始终执行:

// ...
discountTotal = package * discount;
total = package - discountTotal;
cout << "Your total is: " << total << endl;
// ...

相关:What should main() return in C and C++?

答案 1 :(得分: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;
    }
    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;
}

无论用户输入什么,您都在输出总数...希望它有所帮助!