首页 > 解决方案 > 如何阻止我的程序返回到应该完成执行的函数?

问题描述

我对编码很陌生,我编写了一个程序,该程序应该询问用户员工的数量,他们的缺勤天数,然后计算平均缺勤天数。但是,在已经向程序提供了员工人数和缺勤天数之后,它会再次询问员工人数。我看过它,不明白它为什么这样做。我将不胜感激任何帮助。谢谢!

#include <iostream>

using namespace std;

int numEmployees();
int daysAbsent(int);
double averageAbsent(int, int);

void main()
{
    cout << "The average of absence days is: " << averageAbsent(numEmployees(), daysAbsent(numEmployees()));
}

int numEmployees()
{
    static int employees;
    cout << "Enter the number of employees: ";
    cin >> employees;

    while (employees < 1)
    {
        cout << "Please enter a number greater than or equal to 1: \n";
        cin >> employees;
    }

    return employees;
}

int daysAbsent(int employees)
{
    int sumDays = 0;
    int employeeAbsent;

    for (int counter = 1; counter <= employees; counter++)
    {
        cout << "How many days was employee no. " << counter << " absent?\n";
        cin >> employeeAbsent;

        while (employeeAbsent < 0)
        {
            cout << "Please enter a positive value: \n";
            cin >> employeeAbsent;
        }

        sumDays += employeeAbsent;
    }

    return sumDays;
}

double averageAbsent(int employees, int sumDays)
{
    double average = (double)sumDays / employees;
    return average;
}

标签: c++function

解决方案


这是你的问题:

averageAbsent(numEmployees(), daysAbsent(numEmployees())

这说明:

  • 调用numEmployees所以它返回的值可以传递给averageAbsent
  • 调用numEmployees所以它返回的值可以传递给daysAbsent

如果您想多次使用一个值,请将其存储在一个变量中。


推荐阅读