c ++ if循环和函数

时间:2013-03-25 22:00:39

标签: c++ function if-statement

在我的计划中,它首先要求员工人数。 if循环表示如果输入输入< 1输出说“请输入至少1的值”。如果您输入0或-1,则输出供用户更正,但它只执行一次。因此,如果用户输入-1两次,它将第二次运行。它也使用第二个if循环执行此操作。

#include <iomanip>
#include <iostream>

using namespace std;

int getNumEmployees();
int getDaysMissed(int);
double getAverageDays(int,int);

int main()
{
    int numEmployees;
    int daysMissed;
    double average;

    //Get the number of employees
    numEmployees = getNumEmployees();

    //Get the number of days missed
    daysMissed = getDaysMissed(numEmployees);

    //Get the average days missed
    average = getAverageDays(numEmployees, daysMissed);

    cout << "The average number of days missed is: " << average << endl;

    system("pause");
    return 0;
}

int getNumEmployees()
{
    int employeeNum;

    cout << "Enter the number of company employees: ";
    cin >> employeeNum;

    if(employeeNum < 1)
    {
        cout << "Please enter a value greater than 0 " << endl;
        cin >> employeeNum;
    }

    return employeeNum;
}


int getDaysMissed(int employeeNum)
{
    int totalDays = 0;
    int employee;

    for(int count = 1; count <= employeeNum; count++)
    {
        cout << "Enter the number of days employee " << count << " missed: ";
        cin >> employee;
        if(employee < 0)
        {
            cout << "Enter a positive number for days missed " <<     endl;
            cin >> employee;
        }

        totalDays += employee;
    }
    return totalDays;
}

double getAverageDays(int employeeNum, int totalDays)
{
    double averageDays;
    averageDays = totalDays / employeeNum;
    return averageDays;
}

1 个答案:

答案 0 :(得分:2)

改变这个:

if(employeeNum < 1)

到此:

while(employeeNum < 1)

你想要循环。正如克里斯提到的那样,if没有循环。