CS50 'Hours' Practice Problem

#include <cs50.h>
#include <ctype.h>
#include <stdio.h>

float calc_hours(int hours[], int weeks, char output);

int main(void)
{
    int weeks = get_int("Number of weeks taking CS50: ");
    int hours[weeks];

    for (int i = 0; i < weeks; i++)
    {
        hours[i] = get_int("Week %i HW Hours: ", i);
    }

    char output;
    do
    {
        output = toupper(get_char("Enter T for total hours, A for average hours per week: "));
    }
    while (output != 'T' && output != 'A');

    printf("%.1f hours\n", calc_hours(hours, weeks, output));
}

// TODO: complete the calc_hours function
float calc_hours(int hours[], int weeks, char output)
{

}

This part of the implementation details is confusing me:

" To complete calc_hours , first total up the hours saved in the array into a new variable. Then, depending on the value of output , return either this sum, or the average number of hours."

Can someone help me understand?

You are giving the user a prompt:

Enter T for total hours, A for average hours per week:

If they enter T then you want to show them the total hours. If they enter A then you want to show them the average per week.

float calc_hours(int hours[], int weeks, char output)
{
    for (int i = 0; i < hours; i++)
    {
        if (output = T)
        {
            return hours;
        }
        if (output = A)
        {
            average = hours / weeks;
            return average; 
        }
    }
}

Ahhh so something like this?

float calc_hours(int hours[], int weeks, char output)
{
    float total_hours = 0.0;
    for (int i = 0; i < hours; i++)
    {
        if (output = T)
        {
            total_hours += hours;
            return total_hours;
        }
        if (output = A)
        {
            average = hours / weeks;
            return average;
        }
    }
}

Still feeling lost, I thought this would work but it’s not close

**

float calc_hours(int hours[], int weeks, char output)
{
    float total_hours[0] = 0.0;
    for (int i = 0; i < hours; i++)
    {
        if (output = T)
        {
            total_hours += hours;
        }
        return total_hours;
        
        if (output = A)
        {
            average = hours / weeks;
        }
        return average;
    }
}

Got it

float calc_hours(int hours[], int weeks, char output)
{
    float total_hours = 0;
    float average = 0;

    for (int i = 0; i < weeks; i++)
    {
            total_hours += hours[i];
        }
        if (output == 'T')
        {
        return total_hours;
        }
        if (output == 'A')
        {
            average = total_hours / (float) weeks;
        }
        return average;
    }

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.