Yasemin Bishop
Yasemin Bishop

Reputation: 1

How can I stop my program from going back to a function that should be finished executing?

I am pretty new to coding, and I have written a program that is supposed to ask the user for the number of employees, their absent days, and then calculate the average number of absent days. However, it asks for the number of employees a second time after already providing the program with the # of employees and their absent days. I've looked over it and don't understand why it is doing this. I would appreciate any help. Thanks!

#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;
}

Upvotes: 0

Views: 47

Answers (1)

Scott Hunter
Scott Hunter

Reputation: 49848

This is your problem:

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

This says to:

  • Call numEmployees so the value it returns can be passed to averageAbsent
  • Call numEmployees so the value it returns can be passed to daysAbsent

If you want to use a value more than once, store it in a variable.

Upvotes: 1

Related Questions