【问题标题】:How to find standard deviation in C++?如何在 C++ 中找到标准差?
【发布时间】:2015-05-13 02:05:02
【问题描述】:

这是我第一次尝试编程。我希望能够输入可变数量的数据并输出平均值和标准偏差。我希望它尽可能简单,最好使用当前程序中已经存在的命令。

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    float num[46];
    float amount_num;

    cout<< "How many numbers do you want? (max 45)\n";
    cin>> amount_num;

    for (int counter =0; counter < amount_num; counter++)
    {
        cout<< "Enter value "<< counter<< ":"<< endl;
        cin>> num[counter];
    }

    int total;
    int average;
    int latot;
    int fun;
    int n;
    int taco;
    int sd;
    int bell;

    for(int t= 0; t< amount_num; t++)

    {
        total = total + num[t];
    }

    average= total/amount_num;

    for(int t= 0; t< amount_num; t++)


    {
        latot =  num[t] - average;
        bell = pow (latot,2);
        fun = fun + bell;
    }

    n=amount_num-1;
    taco=fun/n;
    sd=sqrt(taco);

    cout<< "Average: "<< average<< endl;
    cout<< "SD: "<< sd<< endl;
}

【问题讨论】:

  • 这次尝试有什么问题?你有错误吗?意外的结果/行为?回复:代码,我不喜欢空格(我在运算符的两边各占一个空格,例如n = amount - 1;),命名(latottaco?!),以及分配一个大,不必要的数组。不过,好的开始;欢迎来到 C++! :)
  • 看起来您正在计算 sample 标准差。如果你没有得到你期望的结果,那么也许你想计算 population 标准差?

标签: c++ statistics standard-deviation


【解决方案1】:

您的代码逻辑看起来是正确的。但是,您不应该使用整数变量。相反,使用浮点变量。使用整数变量会导致大量整数除法,从而导致大量数值截断错误。

例如,对于average= total/amount_num,如果total 是128,amount_num 是10,那么average 将是12,而它应该是12.8。在计算值偏差时会传播截断错误,num[t] - average

taco=fun/n 中发现了类似的整数除法问题。

使用浮点变量消除了整数除法和这些中间数值错误。

【讨论】:

  • 为什么要投反对票?这是一个很好的答案。您不应该使用 int,而是使用 float 或 double!
猜你喜欢
  • 2016-03-27
  • 1970-01-01
  • 2021-03-17
  • 2015-06-27
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
  • 2013-07-15
  • 1970-01-01
相关资源
最近更新 更多