arrays - 数组旋转与获取数组 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[]);
解决方案
按照以下方式设计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*
推荐阅读
- android-studio - 如何从 Android Studio 对 Flutter 项目的分析中排除文件?
- c# - 从网页嵌入/播放声音(如 Amazons 数字音乐样本)
- javascript - 刷新后 Material-UI 中断
- json - 未捕获的引用错误:Jsonbody 未在 Request.request 中定义
- machine-learning - 怎么处理
文本生成中的标记 - styles - 使用 mini-css-extract-plugin 提取本地和全局样式
- java - 使用 JTextPane 正确创建 Class、JTree、DefaultTreeCellRenderer
- javascript - 如何阻止旧的 Firestore 更新覆盖新的本地数据?
- java - 将用户字符串输入到循环数组中
- perl - Net::RawIP 错误地填充源 mac-address (Ubuntu)