数组最后一个元素自动获取垃圾 [英] Array last element automatically gets garbage

查看:54
本文介绍了数组最后一个元素自动获取垃圾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了此输出

学习如何使用数组后,我进行了一个练习来检查数组是否按升序排列,这是我得到的结果,但我找不到问题.

Learning how to use arrays and I got an exercise to check if the array is in an ascending order, after the first run, this is what I got and I cant find the problem.

当我打印数组时,它在最后一个数组中显示一些垃圾.

when I'm printing the array it shows in the last array some garbage.

#include <iostream>

using namespace std;

const int CAPACITY1 = 5;

int main()
{

int arr1[CAPACITY1];
bool a = false;

//init the first input
cout << "Enter 6 numbers: " << endl;
cin >> arr1[0];
int max = arr1[0];
int NoE = 1;

//init the loop to insert numbers
for (int i = 1; i <= CAPACITY1; i++) {
    cout << "Enter 6 numbers: " << endl;
    cin >> arr1[i];
    NoE++;

    //check if input is bigger than max
    if (arr1[i] > max) 
        max = arr1[i];
    else
        a = true;
}

if (a == true)
    cout << "The array is not in an ascending order" << endl;
else
    cout << "The array is in an ascending order" << endl;

cout << NoE;

//end
cout << endl;
return 0;
}

推荐答案

您的循环从1到5:

for (int i = 1; i <= CAPACITY1; i++) {
    cout << "Enter 6 numbers: " << endl;
    cin >> arr1[i];

因此,您只输入五个数字,并且从未将任何内容放入 arr1 [0] 中,并且确实将某些内容放入了 arr [5] 中,这是无效的.

So you only enter five numbers and you never put anything in arr1[0] and you do put something in arr[5] which is invalid.

除此之外,我怀疑您可能错过了练习的重点.如果这是一项家庭作业,那么我想他们会希望您遍历现有数组并报告其是否按升序排列.

Aside from that, I suspect you may have missed the point of the exercise. If this is a homework assignment then I imagine they want you to iterate over an existing array and report if it is in ascending order.

这篇关于数组最后一个元素自动获取垃圾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆