简单的程序比较阵列运行但给出不正确的结果



简单的代码比较每个星期日的小时日志,记录了从一周到下一个星期的改进数量。

我尝试打印阵列以查看其是否正确,但已将其随机无关数字打印出来

//计划将数组代表小时数的程序依次运行。创纪录的天数比前几天还要多。

#include <iostream>
#include <iomanip>
using namespace std;
int main(){
    int nr_progress;
    int times [5];
    cout << "Enter the track times you set for the last 5 Sundays: "<< flush;
    for(int i=0; i<5; i++){
       cin >> times[0];
        }
    for(int l=1; l<4; l++){
        if(times[l] > times [l-1]){
            nr_progress += 1;
        }
    }
std :: cout << "The number of progress days is equal to: " << nr_progress << endl;
}

对于输入7 9 13 12 8.我希望输出为2,但程序正在输出1。

您在第一个循环中有一个简单的错字:

for(int i=0; i<5; i++){
    cin >> times[0];
}

应该是:

for(int i=0; i<5; i++){
    cin >> times[i];
}

您仅在数组中初始化第一个值。然后,当您尝试打印值时,您只是在访问非初始化的内存,这就是为什么您会看到一些随机的垃圾值。

编辑:

您还忘记了Intial nr_progress

int nr_progress = 0;

始终总是初始化您的变量,几乎没有任何理由只是声明一个。

最新更新