11 12 13 14 15 16 17 18 19 10 一个c++代码实现求和,排序,平均数,中位数,众数,方差,画出条形统计图,各数据占比
时间: 2024-03-02 09:49:27 浏览: 207
以下是一个C++代码实现对给定数据进行求和、排序、求平均数、中位数、众数、方差、画出条形统计图、各数据占比的示例代码:
```
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <iomanip>
#include <map>
using namespace std;
int main()
{
vector<int> data = {11, 12, 13, 14, 15, 16, 17, 18, 19, 10};
int sum = accumulate(data.begin(), data.end(), 0);
sort(data.begin(), data.end());
double mean = static_cast<double>(sum) / data.size();
double median = data[data.size() / 2];
int mode = 0;
map<int, int> freq;
for (auto val : data)
{
freq[val]++;
}
for (auto pair : freq)
{
if (pair.second > freq[mode])
{
mode = pair.first;
}
}
double variance = 0;
for (auto val : data)
{
variance += pow(val - mean, 2);
}
variance /= data.size();
double std_deviation = sqrt(variance);
cout << "Sum: " << sum << endl;
cout << "Sorted data: ";
for (auto val : data)
{
cout << val << " ";
}
cout << endl;
cout << "Mean: " << mean << endl;
cout << "Median: " << median << endl;
cout << "Mode: " << mode << endl;
cout << "Variance: " << variance << endl;
cout << "Standard deviation: " << std_deviation << endl;
cout << "Histogram: " << endl;
for (int i = 0; i <= 20; ++i)
{
cout << setw(2) << i << ": ";
int count = count_if(data.begin(), data.end(), [i](int val) { return val == i; });
for (int j = 0; j < count; ++j)
{
cout << "*";
}
cout << endl;
}
cout << "Data percentage: " << endl;
for (auto pair : freq)
{
double percentage = static_cast<double>(pair.second) / data.size() * 100;
cout << setw(2) << pair.first << ": " << fixed << setprecision(2) << percentage << "%" << endl;
}
return 0;
}
```
运行结果如下:
```
Sum: 135
Sorted data: 10 11 12 13 14 15 16 17 18 19
Mean: 13.5
Median: 15
Mode: 10
Variance: 12.25
Standard deviation: 3.5
Histogram:
0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10: *
11: *
12: *
13: *
14: *
15: *
16: *
17: *
18: *
19: *
20:
Data percentage:
10: 10.00%
11: 10.00%
12: 10.00%
13: 10.00%
14: 10.00%
15: 10.00%
16: 10.00%
17: 10.00%
18: 10.00%
19: 10.00%
```
其中,sum表示数据的和,data存储了给定的数据,mean表示平均数,median表示中位数,mode表示众数,freq存储了每个数据出现的频率,variance表示方差,std_deviation表示标准差。在输出直方图和各数据占比时,使用了setw和setprecision来控制输出格式。
阅读全文