C 如何返回在数组中获得最佳和的索引?
我只需要输入一个数组,让程序返回产生最大和的索引范围 例子 对于A={5,-6,7,-5,10,-1}–最佳和由A[2..4]中的值组成,总值为7+-5+10=12 对于A={1,2,4,-6,4,2,1}–最佳和由[0..6](整个数组)中的值组成,总共为8 对于A={5,2,-3,1,-5,4,-2}–最佳和由A[5]中的值组成,总共为4 如果有人能帮我返回以下值,我将不胜感激 这是我的代码(似乎运行不正常)C 如何返回在数组中获得最佳和的索引?,c,arrays,C,Arrays,我只需要输入一个数组,让程序返回产生最大和的索引范围 例子 对于A={5,-6,7,-5,10,-1}–最佳和由A[2..4]中的值组成,总值为7+-5+10=12 对于A={1,2,4,-6,4,2,1}–最佳和由[0..6](整个数组)中的值组成,总共为8 对于A={5,2,-3,1,-5,4,-2}–最佳和由A[5]中的值组成,总共为4 如果有人能帮我返回以下值,我将不胜感激 这是我的代码(似乎运行不正常) #包括 int_资源集合(int arr[],int len){ int最高,开始
#包括
int_资源集合(int arr[],int len){
int最高,开始,结束,i,结果;
最高=arr[len-1];//最高值的限制
开始=len-1;
end=len-1;//总索引中的所有变量
对于(i=0;i好的,您有一些错误
首先,在printf(“%d”)中,_resource_集合(&a[6],length));
只向函数传递数组的第六个元素
另外,您的for
循环没有考虑数组的所有元素。最后,您还需要将开头和结尾保存在int
数组中
下面是我将如何做到这一点(我已经用您提供的3个输入对其进行了测试,输出与预期一致!):
#包括
int*资源集合(int arr[],int len){
int最高;
int返回值[2];
int i;
INTA;
int结果;
最高=arr[len-1];//最高值的限制
returnvalue[0]=len-1;
returnvalue[1]=len-1;//总索引中的所有变量
对于(i=0;i最高)
{
最高=结果;
返回值[0]=i;
返回值[1]=a-1;
}
结果=0;
}
返回值;
}
int main()
{
inta[7]={5,-6,7,-5,10,-1};
整数长度=7;
printf(“A[%d..%d]\n”、资源集合(A,长度)[0],资源集合(A,长度)[1]);
}
如果您不理解我写的内容,或者需要更多帮助,请说出来。此调用:printf(“%d”,资源集合(&a[6],长度))
毫无意义,你正在传递一个指向数组末尾一个元素的指针?它应该是a
。我看到一个double返回值了吗
?每个函数只能返回一个变量。一行两个返回值既没用又让人困惑。对不起;;我只是刚刚开始C编程..我只是想找到一个y使我的函数返回“开始”和“结束”的值。如果你想返回两个不同变量的值,你可以使用一个结构或一个2个整数的数组。你可能是C新手,但你的逻辑思维中也有与C无关的错误。例如,result=arr[i]+arr[a];
将只生成两个数组元素的结果,而不是元素序列的结果。
#include<stdio.h>
int the_resource_collection( int arr[], int len){
int highest, start, end, i, result;
highest = arr[len-1];// the limits of the highest value
start = len - 1;
end = len - 1;// all the variables in the total indexes
for( i=0; i<len-2; i++)
{
for (a=i; a<len-1; a++)
{
result= arr[i]+ arr[a];// try to find the total of the index
{
if (result > highest)
{
highest = result;
start = i;
end = a;
}
}
}
}
return start;
return end;
}
int main()
{
int a[6] = {5, -6, 7, -5, 10, -1};
int length = 6;
printf("%d",the_resource_collection(&a[6],length));
}
#include<stdio.h>
int * the_resource_collection( int arr[], int len){
int highest;
int returnvalue[2];
int i;
int a;
int result;
highest = arr[len-1];// the limits of the highest value
returnvalue[0] = len - 1;
returnvalue[1] = len - 1;// all the variables in the total indexes
for( i=0; i<len; i++)
{
result= arr[i];
for (a=i+1; a<len; a++)
{
if (result > highest)
{
highest = result;
returnvalue[0] = i;
returnvalue[1] = a-1;
}
result+=arr[a];
}
if (result > highest)
{
highest = result;
returnvalue[0] = i;
returnvalue[1] = a-1;
}
result=0;
}
return returnvalue;
}
int main()
{
int a[7] = {5, -6, 7, -5, 10, -1};
int length = 7;
printf("A[%d...%d]\n",the_resource_collection(a,length)[0],the_resource_collection(a,length)[1]);
}