gpt4 book ai didi

c++ - 比较正在运行但给出错误结果的数组的简单程序

转载 作者:行者123 更新时间:2023-11-30 04:45:26 27 4
gpt4 key购买 nike

用于比较每个星期天运行的小时日志的简单代码,记录一周到下一周的改进次数。

我尝试打印数组以查看其是否正确,但打印出的随机无关数字

//采用表示小时的数组的程序在每个星期六按顺序运行。记录比前几天运行更多的天数。

#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 循环中有一个简单的拼写错误:

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

应该是:

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

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

编辑:

您还忘记初始化 nr_progress,使用:

int nr_progress = 0;

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

关于c++ - 比较正在运行但给出错误结果的数组的简单程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57270838/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com