以写统计学算法代码来讲解一些考试中可能用到的库函数0——平均数,中位数,众数

来源:互联网 发布:2016云计算技术大会 编辑:程序博客网 时间:2024/05/29 13:58

源代码的链接见https://www.hackerrank.com/challenges/s10-basic-statistics/editorial

题目给定的输入如下:

Input FormatThe first line contains an integer, N, denoting the number of elements in the array. The second line contains N space-separated integers describing the array's elements.

要求输出这组数列的平均数,中位数,众数

代码可见链接,我在这里复制粘贴一下

#include <iostream>#include <map>#include <vector>#include <algorithm>#include <iomanip>using namespace std;int main() {    int n;    cin >> n;        vector<int> a(n);        for (int i = 0; i < n; i++) {        cin >> a[i];    }        sort(begin(a), end(a));        double sum = accumulate(begin(a), end(a), 0);    double average = sum / n;        double median = a[n / 2];        if (! (n & 1)) {        median += a[n / 2 - 1];        median /= 2;    }        map<int, int> f;        for (int e : a) {        f[e]++;    }        int mode = 0;        for (auto e : f) {        if (e.second > f[mode]) {            mode = e.first;        }    }        cout << setprecision(1) << fixed << average << endl;    cout << setprecision(1) << fixed << median << endl;    cout << mode << endl;        return 0;}
0.首先是一个vector的问题,在cpp中,你无法这么声明一个数组:
int n;cin >> n;int a[n];

如果你需要动态声明数组的话,最上面的代码可能有用,即
    int n;    cin >> n;        vector<int> a(n);

1.sort函数,详情请自己看一下cppreference,这个函数可以实现整数的排序,也可以实现类的排序;当然,这个函数也能指定排序的顺序,具体的可以自己研究。

2.accumulate函数,这个函数可以用来实现很多奇怪的功能,在这里是做求和用的
    double sum = accumulate(begin(a), end(a), 0);
可能很多人在没有用过这个函数的情况下不知道0的含义,0是指初始化时sum的值

这个函数也可以用来做乘法,当然具体样例可以自己去cppreference上看一看。

其实你不用这个函数也是能自己实现求和的对吧。

3.auto 这是一个关键词,不是一个函数,提出来讲一下是因为可能在教学的时候,老师压根不会提到这个,因为这个关键词应该是从C++11开始使用的,而我们课上讲的C++可能不会涉及到比较新的内容。

4.setprecision,这个百度百科上讲的很清楚,与fixed连用可以控制小数点后输出位数。

阅读全文
0 0
原创粉丝点击