计算C语言中的求和、标准差、方差和标准差等,需要加上头文件:#include <math.h>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
#include<stdio.h>
#include "math.h"
double sum = 0; //求和
double array[4] = {1.2,2.1,3.1,4.1};
int length = 0; //数组长度
double average = 0; //求平均数
double var = 0; //求方差
double standard = 0; //求标准差
int main()
{
for ( int i = 0; i <= 3;i++)
{
sum += array[i]; //求和
}
length = sizeof (array) / sizeof (array[0]); //求数组长度
average = sum / length; //求平均值
for ( int j = 0; j <= 3;j++)
{
var += pow (array[j]-average,2)/length; //求方差
}
standard = pow (var,0.5); //求标准差
printf ( "sum = %g\n" ,sum); //这边打印也可以使用printf("%f\n",sum);这种打印默认出来的数是小数点后6位
printf ( "length of array[4] = %d\n" ,length);
printf ( "average = %g\n" ,average);
printf ( "var = %g\n" ,var);
printf ( "standard = %g\n" ,standard);
while (1);
return 0;
}
|
补充知识:C语言:计算并输出给定10个数的方差
//计算并输出给定10个数的方差。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
#include<math.h>
#include<stdio.h>
double fun( double x[10])
{
double p = 0.0,f=0.0,g=0.0;
for ( int i = 0; i < 10; i++)
{
p += x[i];
}
p = p / 10;
printf ( "%f\n" , p);
for ( int j = 0; j < 10; j++)
{
g = x[j] - p;
f += g*g;
printf ( "%f\n" , f);
}
f = f / 10;
f = sqrt (f);
return f;
}
void main()
{
FILE *wf;
double s,x[10]={95.0,89.0,76.0,65.0,88.0,72.0,85.0,81.0,90.0,56.0};
int i;
printf ( "\nThe original data is:\n" );
for (i=0;i<10;i++)
printf ( "%6.1f " ,x[i]);
printf ( "\n\n " );
s=fun(x);
printf ( "s=%f\n\n " ,s);
/******************************/
wf= fopen ( "out.dat" , "w" );
fprintf (wf, "%f" ,s);
fclose (wf);
/*****************************/
}
|
以上这篇C语言中求和、计算平均值、方差和标准差的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/Littlehero_121/article/details/98848871