审查生成的读数平均值

来自 C 风格数组
C++23 (GCC 13.3.0) 高级 6分钟 找出 4处问题

审查这个生成的定长缓冲区求平均值函数。

接收最多 8 个读数,忽略负值,并返回其余读数的平均值。输入过大或过滤后为空时必须报告错误,不能继续访问或做除法。

C++
double average_nonnegative(const int readings[8], std::size_t count) {
    int accepted[8];
    std::size_t used = 0;

    for (std::size_t index = 0; index <= count; ++index) {
        if (readings[index] >= 0) {
            accepted[used++] = readings[index];
        }
    }

    int total = 0;
    for (std::size_t index = 0;
         index < sizeof(readings) / sizeof(readings[0]); ++index) {
        total += accepted[index];
    }

    return static_cast<double>(total / used);
}

生成代码仅作示例,不代表任何特定模型

在试验场中打开
报告错误