首页 > 代码库 > average and standard deviation-平均数和标准差

average and standard deviation-平均数和标准差

average and standard deviation-平均数和标准差(4个数),允许重复计算:

//average and standard deviation-平均数和标准差
#include<iostream>
#include<cmath>
using namespace std;

double average(double s1,double s2,double s3,double s4);
double standard_deviation(double s1,double s2,double s3,double s4,double average);

int main()
{
    double s1,s2,s3,s4;
    double ave,sta_dev;
    char ans;
    
    do{
        cout<<"Please input four numbers:\n";
        cin>>s1>>s2>>s3>>s4;
        
        ave = average(s1,s2,s3,s4);
        sta_dev = standard_deviation(s1,s2,s3,s4,ave);
        
        cout<<"The average is "<<ave<<endl;
        cout<<"The standard deviation is "<<sta_dev<<endl;
        
        cout<<"Do you want again?";
        cin>>ans;
    }while(‘y‘ == ans || ‘Y‘ == ans);
    
    return 0;
}

double average(double s1,double s2,double s3,double s4)
{
    return (s1+s2+s3+s4)/4;
}

double standard_deviation(double s1,double s2,double s3,double s4,double average)
{
    return sqrt((pow((s1 - average),2) + pow((s2 - average),2) + pow((s3 - average),2) + pow((s4 - average),2))/4);
}

结果:

Please input four numbers:
1 2 3 4
The average is 2.5
The standard deviation is 1.11803
Do you want again?y
Please input four numbers:
12.3 13.4 10.5 9.0
The average is 11.3
The standard deviation is 1.68375
Do you want again?y
Please input four numbers:
5 5 5 5
The average is 5
The standard deviation is 0
Do you want again?


average and standard deviation-平均数和标准差