C++将数组重置为null

C++ Reset array to null

本文关键字:null 数组 C++      更新时间:2023-10-16

我正在试图找到平均值,它适用于我输入的第一组数字,但第二组数字略有偏离,我认为这是因为我没有正确重置数组,或者我错过了重置数组中的一个值。

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    int array [15];
    int amount, step, length;
    double total;
    step = -1;
    amount = 0;
    length = 0;
    total = 0;
    cin >> amount;
    for(int count = 0; count!=amount; count++){
        while (array[step] != 0){
            step++;
            cin >> array[step];
        }
        length = step;
        while (step >= 0){
            total = total + array[step];
            array[step] = 0;
            step--;
        }
        total = total / length;
        cout << round(total) << " ";
        step = -1;
    }

    return 0;
}
step = -1;

代码的第一个过程

while (array[step] != 0){

产生未定义的行为。数组的第一个条目应使用0进行索引。