简体   繁体   中英

Why is the number declared in the double function not used? (C)

#include <stdio.h>

double calculate_average (int number)
{
    static int numberInput = 0; //counter
    static int sum = 0;
    sum = sum + numberInput;
    numberInput++;
    return sum / numberInput;
    // calculate and return average so far.
}
int main(void)
{
    double average;
    while (1)
    {
        int number;
        scanf("%d", &number);
        if (number == 0)
            break; //stops if number == 0
        else
            average = calculate_average(number);
    }
    printf("%.1f\n", average);
    return 0;
}

As I can personally tell, the function is trying to calculate the average. But why does the main function not use the number in the calculate_average function?

As written, your calculate_average function does not use its given number argument because, nowhere in that function, do you instruct it to do so. Most likely, your sum = sum + numberInput; should really be sum = sum + number; (thus adding that given number to the running total).

A couple of other points:

  1. You should initialize your average variable (to 0.0), otherwise you'll get a crazy result if you give your program an empty list (ie give zero as the first entry).
  2. As your function returns a double , it is best to have the sum variable also as a double ; otherwise, you are performing integer arithmtic in your calculation, and all returned values will be truncated to integers (losing any fractional parts).
  3. Others will likely point out that you should always check the value returned by your scanf call (it will be 1 if the read operation succeeds) and add code to handle any error; however, addressing that point here is, IMHO, beyond the 'remit' of this question, but see this answer to How validate user input when the expected value is of type int and the entered value is not of type int? .

Here's a possible working version:

#include <stdio.h>

double calculate_average(int number)
{
    static int numberInput = 0; //counter
    static double sum = 0.0;
    sum = sum + number;
    numberInput++;
    return sum / numberInput;
    // calculate and return average so far.
}

int main(void)
{
    double average = 0.0; // Always best to initialize variables!
    while (1)     {
        int getal;
        scanf("%d", &getal);
        if (getal == 0)
            break; //stops if getal == 0
        else
            average = calculate_average(getal);
    }
    printf("%.1f\n", average);
    return 0;
}

Please feel free to ask for any further explanation and/or clarification.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM