简体   繁体   English

我++; AVE + =值; AVE / = I; 在C中没有给出预期的结果

[英]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. 我是C语言的新手,我坚持从事一些我认为较有经验的用户可以轻松解决的问题。

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). 然后可以随时将平均值计算为sum / 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. 如第一段所述,您似乎正在使用混合函数,或者错误地将总和除以计数,或者在添加下一个值之前未将平均值转回总和。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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