Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

loops - Function that would get minimum, maximum and average in c

Hello I wrote a function that continuously accepts integer inputs from the user until the user enters -999 (sentinel value). The function also identifies the highest and lowest value entered, the average of inputs. I already wrote a code for it but I can't seem to get the correct average value for it and need help revising it.

Here's my code:

#include <stdio.h>

int getMinMaxAve ( int *min, int *max, float *ave)
{
    int nVal;
    int nMin = 0;
    int nMax = 0;
    int nResult = 1;
    int nCount = 0;

    while (nVal != -999)
{
    printf ("Value:");
    scanf ("%d", &nVal);
    
    if (nVal !=-999) 
    {
        if (nVal > nMax)
            nMax = nVal;
        if (nVal < nMin)
            nMin = nVal;
        nResult += nVal;
        nCount += 1;
        
    }
}
        *min = nMin;
        *max = nMax;
        *ave = nResult / nCount;
}


int main ()
{
        int nMin;
        int nMax;
        int nResult;
        float fAve;

        nResult = getMinMaxAve (&nMin, &nMax, &fAve);

if (nMin == -999)
{
    printf ("Min: NA
");
    printf ("Max: NA
");
    printf ("Average: NA
");
}
else 
{
    printf ("Min: %d
", nMin);
    printf ("Max: %d
", nMax);
    printf ("Average: %f
", fAve);
}

return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First the variable you keep the sum in nResult is initialized at 1. That must absolutely be zero.

Second *ave = nResult / nCount; does integer division as both nResult and nCount are integers.

A way out of this is to declare nResult as float. Then that same expression actually does what you expect it to do. And better rename that variable to totalSum, or something equally informative.

(But you better use double instead of float everywhere)

There are more problems with your code, but I limit myself to just answer your question about the average.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...