简体   繁体   中英

i++; ave+=value; ave/=i; in C don't give expected result

I am new to C and I stuck on something which I believe a bit more experienced user can resolve easily.

I am in attempt to write a code which based on a given price could calculate it's value with Sale tax and an average price in total. Here's my problem for the average works only for second price and here it stop change it's value.

Any help would be appreciate.

 #include "stdafx.h"

static const double SAZBA = 21;

double plusDPH(double cena);


int _tmain(int argc, _TCHAR* argv[])
{
    double bezDPH=1, sDPH, prumer=0;
    int i = 0;

    while (bezDPH != 0)
    {
        printf("Zadejte cenu bez DPH [Kc]: ");
        scanf("%lf", &bezDPH);
        sDPH = plusDPH(bezDPH);
        printf("Cena s DPH je: %.2lf Kc.\n", sDPH); // With Sale tax

        i++;
        prumer += sDPH;
        prumer /= i; // Average price in total
        printf("Prumerna cena s DPH: %.2lf Kc.\n\n", prumer);
    }

    return 0;
}

double plusDPH(double cena)
{
    cena *= SAZBA / 100 + 1;
    return cena;
}

Thanks a lot!

If you have an average then add a value to it and divide that by the count, you will lose information in the process. You seem to be using a hybrid of the two most common ways of doing it.

The first is to simply maintain the sum rather than the average, along with the count of course. This is probably the most usual case.

The average can then be calculated at any time as sum / count (for non-zero count).

The second is to maintain the average but ensure you apply the value to the recalculated sum, something like:

sum = average * count
sum = sum + value
count = count + 1
average = sum / count

As mentioned in the first paragraph, you appear to be using a hybrid, either erroneously dividing the sum by the count, or not turning the average back into a sum before adding the next value.

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