计算变异系数的 C++ 程序
我们给定了一个大小为 n 的浮点数组,任务是找出变异系数并显示结果。
什么是变异系数?
在统计测量中,变异系数用于通过给定的数据找出变异范围。在金融方面,变异系数用于找出投资额涉及的风险金额。如果标准差与均值之间的比率较低,则投资所涉及的风险也较低。变异系数是标准差与均值之间的比率,由以下公式得出:
变异系数 = 标准差 / 均值
示例
Input-: array[] = { 10.0, 21, 23, 90.0, 10.5, 32.56, 24, 45, 70.0 } Output-: coefficient of variation is : 0.75772 Input-: array[] = { 15.0, 36.0, 53.67, 25.45, 67.8, 56, 78.09} Output-: coefficient of variation is : 0.48177
给定程序中使用的解决方法如下:
- 输入包含浮点值的数组
- 计算给定数组上的均值和标准差
- 通过用标准差除以均值来计算变异系数值
- 将结果作为变异系数显示
算法
Start Step 1-> declare function to calculate the value of mean float cal_mean(float arr[], int size) Declare float sum = 0 Loop For i = 0 and i < size and i++ Set sum = sum + arr[i] End return sum / size Step 2-> declare function to calculate the value of standard deviation float StandardDeviation(float arr[], int size) Declare float sum = 0 Loop For i = 0 and i < size and i++ Set sum = sum + (arr[i] - cal_mean(arr, size)) * (arr[i] - End Call cal_mean(arr, size)) return sqrt(sum / (size - 1)) Step 3-> Declare function to calculate coefficient of variation float CoefficientOfVariation(float arr[], int size) return StandardDeviation(arr, size) / cal_mean(arr, size) Step 4-> In main() Declare an array of float arr[] = { 10.0, 21, 23, 90.0, 10.5, 32.56, 24, 45, 70.0} Calculate the size of array as int size = sizeof(arr) / sizeof(arr[0]) Call function as CoefficientOfVariation(arr, size) Stop
示例
#include <bits/stdc++.h> using namespace std; // function to calculate the mean. float cal_mean(float arr[], int size) { float sum = 0; for (int i = 0; i < size; i++) sum = sum + arr[i]; return sum / size; } //function to calculate the standard deviation float StandardDeviation(float arr[], int size) { float sum = 0; for (int i = 0; i < size; i++) sum = sum + (arr[i] - cal_mean(arr, size)) * (arr[i] - cal_mean(arr, size)); return sqrt(sum / (size - 1)); } // function to calculate the coefficient of variation. float CoefficientOfVariation(float arr[], int size) { return StandardDeviation(arr, size) / cal_mean(arr, size); } int main() { float arr[] = { 10.0, 21, 23, 90.0, 10.5, 32.56, 24, 45, 70.0}; int size = sizeof(arr) / sizeof(arr[0]); cout<<"coefficient of variation is : "<<CoefficientOfVariation(arr, size); return 0; }
输出
coefficient of variation is : 0.75772
广告