首页 > 解决方案 > 数组旋转与获取数组 C 语言的最大值和索引位置

问题描述

我正在创建一个程序来获取数组中最高元素的索引值。

样本输入:

4 (Size of a[])
1 2 4 3 (Elements of a[])
2 (Size of rotate[])
0 2 (Elemnts of rotate[])

输出将是:

2
0

使用左旋转。
在第一次旋转 (0) 中,位置将为 2,因为 4 是最高的 a[1,2,4,3]
在第二次旋转 (2) 中,位置将为 0,因为 4 是最高的 a[4,3, 1,2]

问题是我没有得到想要的输出并且有一个警告for(j=0;j<rotateValue;j++)

我希望功能保持原样并将这部分修复,int* output = getMaxIndex(a,rotate); 但我不知道如何。提前感谢您的帮助!

#include<stdio.h>

int i,j,k; // for looping
int n, m; // sizes of arrays


int getMaxIndex(int* a[], int* rotate[])
{
    int indices[m]; 

                
    for(i=0;i<m;i++)
    {
        int* rotateValue = rotate[i];                           
        for(j=0;j<rotateValue;j++)      // for rotation
        {               
            int* first = a[0];  
            for(i=0;i<n-1;i++)
            {       
                a[i] = a[i+1];
            }
            a[n-1] = first;
        }
                
        int location;
        int* max = a[0];
        for(j=0;j<n;j++) // getting the max element 
        {
            if(a[j] > max)
            {
                max = a[j];
//              printf("Max added");
            }
        }
        
        for(j=0;j<n;j++) // getting the location
        {
            if(max == a[j])
            {
                location = j;
//              printf("Loc added");
            }
        }
        
        
        indices[i] = location;      
    

    }
    
//  for(i=0;i<m;i++) // printing here to know if correct
//  {
//      printf("%d",indices[i]);
//  }
    
    
    
    return *indices;
            
        
    

}

int main()
{
    
    
    scanf("%d",&n); // inputting array size 
    int* a[n];  
    
    for(i=0;i<n;i++) // filling elements of a[]
    {
        scanf("%d",&a[i]);
    }
    
    scanf("%d",&m); // inputting rotate array size
    int* rotate[m];
    
    for(i=0;i<m;i++) // filling elements of rotate[]
    {
        scanf("%d",&rotate[i]);
    }
    

    int* output = getMaxIndex(a,rotate); // call function
    
    for(i=0;i<m;i++) // printing output
    {
        printf("%d",output[i]);
    }
    
}


int getMaxIndex(int* a[], int* rotate[]);

标签: arrayscfunctionrotation

解决方案


按照以下方式设计getMaxIndex()应该可以解决大部分问题:

int* getMaxIndex(int a[], int rotate[])
{
    static int indices[MAX_POSSIBLE_VALUE_OF_M];
    /*
        your code
    */
    return indices;
}

现在,您所要做的就是相应地调整main()函数中的代码。


为什么将数组声明indices[]getMaxIndex()静态 int?

indices[]是 的局部变量getMaxIndex()。所以在getMaxIndex()执行完的return语句后,它就被销毁了。这意味着,如果您返回indices[]main()主函数将无法再访问indices[]。这个问题可以通过声明indices[]为 astatic int而不是来解决int

注意:静态数组应该有恒定的大小。因此,它的大小应该声明为 m 的最大可能值而不是 m。

所需的调整main()

声明a[]androtate[]代替. int_int*


推荐阅读