(C++)输入任意个实数(10~100个),计算平均值,升序输出所有数(包括平均值在内)的问题。
PHP中文网
PHP中文网 2017-04-17 13:15:43
0
3
761

我突然发现自己并不知道如何计算一个数组已经被赋值过的元素个数,求教。百度上也没有搜到这种,都是固定个数算平均数的题目。。。

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(3)
黄舟

If you use a container like Vector, you can directly use its size() method to know the size. If it is an ordinary array, either initialize it to a value that cannot appear in normal data, or add a counter when inputting , calculate the number of input elements

小葫芦
#include <iostream>
#include <algorithm>
#include <cassert>
const int MAXN = 101;
double array[MAXN];
double sum = 0;
int counter = 0;

int main() {
    for (;std::cin >> array[counter]; sum += array[counter++]) {}
    assert(counter != 0);
    array[counter++] = sum / static_cast<double>(counter);
    std::sort(array, array + counter);
    for (int i = 0;i < counter; i++) {
        std::cout << array[i] << " ";
    }
    return 0;
}

Lost the code and run away

巴扎黑
int cnt = 0 ;
double sum = 0 ; 
double a[];
// 未知个数主要是加一个计数器,就是输入一个数计数器cnt加一
while(cin>>n){
    a[cnt] = n;
    cnt ++ ;
    sum += cnt ;
}
// 这部分主要是排序的问题,已经转化成已知个数的数组的排序了,各种排序算法。。
sort();
output()

From a human perspective: enter a number, add one to the quantity
From a code/machine perspective: the quantity is a cnt record, enter a cnt++

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!