gpt4 book ai didi

C++ 数组索引

转载 作者:行者123 更新时间:2023-11-30 02:32:56 25 4
gpt4 key购买 nike

所以我这里有这个简单的程序,我的讲师要求进行以下编辑,但我看不到它:

Sorry, you are missing the point. Since all of your functions are using indexing from 1 to n, where n can be 100, you never use the element with index zero of the array. That means that the maximum number of values you will use in the array is 99. If the user really wants to enter 100 values, your solution then won’t work.

Can you fix your solution again?

 #include <iostream>
using namespace std;
int readnums(int v[]);
void findmaxmin(int v[],int n,int &mi,int &ma);
int findmidsum(int v[],int n,int mi,int ma);
int main()
{
const int ARRAYVALUE=100;
int v[ARRAYVALUE];
int n=readnums(v),mi,ma;
findmaxmin(v,n,mi,ma);
cout<<"Max= "<<ma<<endl;
cout<<"Min= "<<mi<<endl;
cout<<"Middle sum= "<<findmidsum(v,n,mi,ma)<<endl;

}
int readnums(int v[])
{
cout<<"How many numbers to enter: ";
int n=0;

cin>>n;
for(int a=1;a<=n;a++)
{
cout<<"Enter no. "<<a<<": ";
cin>>v[a];
}
return n;
}
void findmaxmin(int v[],int n,int &mi,int &ma)
{
ma=v[1];
mi=v[1];
for(int a=1;a<=n;a++)
{
if(mi>v[a])mi=v[a];
if(ma<v[a])ma=v[a];
}
}
int findmidsum(int v[],int n,int mi,int ma)
{
int s=0;
for(int a=1;a<=n;a++)
if(v[a]!=mi && v[a]!=ma)
s+=v[a];
return s;
}

最佳答案

正如我在评论中提到的,您必须从 a=0 开始迭代至 a<n而不是来自 a=1a<=n .但是您还必须修改以下几行:

ma=v[1];
mi=v[1];

...成为:

ma=v[0];
mi=v[0];

...否则,如您所述,最大计算中断(因为当数组中只有一个索引时 v[1] 不存在)。

这是完整的更新代码:

#include <iostream>
using namespace std;
int readnums(int v[]);
void findmaxmin(int v[],int n,int &mi,int &ma);
int findmidsum(int v[],int n,int mi,int ma);
int main()
{
const int ARRAYVALUE=100;
int v[ARRAYVALUE];
int n=readnums(v),mi,ma;
findmaxmin(v,n,mi,ma);
cout<<"Max= "<<ma<<endl;
cout<<"Min= "<<mi<<endl;
cout<<"Middle sum= "<<findmidsum(v,n,mi,ma)<<endl;
}

int readnums(int v[])
{
cout<<"How many numbers to enter: ";
int n=0;

cin>>n;
for(int a=0;a<n;a++)
{
cout<<"Enter no. "<<a+1<<": ";
cin>>v[a];
}
return n;
}

void findmaxmin(int v[],int n,int &mi,int &ma)
{
ma=v[0];
mi=v[0];
for(int a=0;a<n;a++)
{
if(mi>v[a])mi=v[a];
if(ma<v[a])ma=v[a];
}
}

int findmidsum(int v[],int n,int mi,int ma)
{
int s=0;
for(int a=0;a<n;a++) {
if(v[a]!=mi && v[a]!=ma)
s+=v[a];
}
return s;
}

您可以在这里测试上面的代码:http://cpp.sh/6ogo

关于C++ 数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35922515/

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