我写了这个简单的代码,应该计算一系列数组元素的最高数量,但结果很奇怪

I wrote this simple code that should calculate the highest number of a series of array elements but the results are strange

本文关键字:高数量 数组元素 结果 一系列 简单 代码 计算      更新时间:2023-10-16

我写了这个简单的代码,应该计算一系列数组元素的最高数量,但结果很奇怪,我很确定这与我的写作方式有关,但我无法弄清楚我做错了什么

我在c ++ shell上尝试了相同的代码,它给了我不同的结果

#include <iostream>
using namespace std;
int main()
{
    int size,c,max;
    cout<< "enter the size of the array" << endl;
    cin>> size;
    int a[size];
    max=a[0];
    cout <<"fill the array" << endl;
    for(c=0; c<size; c++){
        cin>>a[size];
        if(max<a[size]){
            max=a[size];
        }
            }
   cout<<"the highest number is:"<<max;
}

输入数组的大小5填充数组12345最高数字是:27进程返回 0 (0x0( 执行时间 : 14.653 s按任意键继续。

输入数组的大小7填充数组1234567最高数字是:27进程返回 0 (0x0( 执行时间 : 14.653 s按任意键继续。

输入数组的大小8填充数组12345678最高数字为:8返回的进程 0 (0x0( 执行时间 : 5.915 s按任意键继续。(如果数组的大小超过 8 它就可以工作(

你循环是错误的,因为你使用数组的大小而不是循环索引c。这就是您的代码应该的样子。

for(c=0; c<size; c++){
    cin>>a[c];
    if(max<a[c]){
        max=a[c];
    }
}

遇到的另一个错误是,在给数组一个值之前,您使用了数组中第一个元素的值。

int a[size];
max=a[0]; // at this point a[0] does not have a value

你应该像这样重新编码

cout <<"fill the array" << endl;
cin>>a[0];
max=a[0];
for(c=1; c<size; c++){
    cin>>a[c];
    if(max<a[c]){
        max=a[c];
    }
}

现在,只有在您为其指定值后才使用a[0],并且循环已更改为从c=1开始。

我不

熟悉C++,但我会指出你遇到的问题:

for(c=0; c<size; c++){
    cin>>a[size];
    if(max<a[size]){
        max=a[size];
    }
        }
cout<<"the highest number is:"<<max;
这始终将输入放入数组

的最后一项,因此您不再跟踪输入(如果需要(,您应该将循环变量放入索引中以进行最大比较和数组存储操作。

另一个问题是您使用max=a[0];但它尚未填充。当您使用负值或取决于语言的嵌入时,这可能是一笔交易。

看到的另一个问题(我不确定,但在 C 中发生在我身上(是你正在创建一个这样的数组:

int size,c,max;
cout<< "enter the size of the array" << endl;
cin>> size;
int a[size];

如果我是对的(根据我的 C 经验(,这不应该以这种方式完成,因为你的数组是在编译时创建的,但 size 的值还没有初始化,写在内存中不应该写的某个地方。顺便说一下,这可能会导致"27"问题。

首先建议您像这样创建数组,它将在每个索引处用 0 初始化数组,因为访问空索引可能会产生未定义的行为:

int a[size] = {0};

其次,你在循环中使用 size 作为数组的索引,你应该使用你递增的值 (c( 来访问每个索引。也许你可以使用后来的 c++ 标准并像这样编写它(用于每个(:

for (auto &singleInput : a) // access by reference to avoid copying
{  
    cin >> singleInput;
    if(max < singleInput)
    {
        max = singleInput;
    }
}