我到处搜索,不确定是为什么大小为7的数组可用于6个索引,而6个不会。

#include <iostream>

using namespace std;


int main() {

    double rainRate[6];
    double averageRainfall = 0.0;

    for (unsigned int i = 0; i <= 6; i++) {
        cout << "Enter rainfall rate for day: " << i << endl;
        cin >> rainRate[i];

        if ((rainRate[i]) >= 6.0) {
            cout << "Rainfall rate is High" << endl;
        } else if (rainRate[i] < 6.0 && rainRate[i] > 3.0) {
            cout << "Rainfall rate is Medium" << endl;
        } else if (rainRate[i] <= 3.0) {
            cout << "Rainfall rate is Low" << endl;
        }

        averageRainfall += rainRate[i];
    }

    cout << "The average rainfall rate for this week is:  " << endl;
    cout << (averageRainfall / (double) 7);

    return 0;
}


当将数组的大小更改为7并将值分配给6个索引时,这将毫无问题地运行,但是如果使用数组的确切大小,则会导致分段错误。

最佳答案

因为double rainRate[6];的大小为6,但是您的代码尝试访问7个项目:[0][1][2][3][4][5][6]

如果您有一个n元素数组,则有效索引为0-n-10-5在您的情况下。

解决方案:将i <= 6替换为i < 6

10-08 14:31