search

Home  >  Q&A  >  body text

(C++)输入任意个实数(10~100个),计算平均值,升序输出所有数(包括平均值在内)的问题。

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

PHP中文网PHP中文网2767 days ago766

reply all(3)I'll reply

  • 黄舟

    黄舟2017-04-17 13:17:43

    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

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 13:17:43

    #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

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 13:17:43

    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++

    reply
    0
  • Cancelreply