【问题标题】:Cyclic Right Shift for C for an array- time exceeds-infinite loop?数组时间超过无限循环的 C 循环右移?
【发布时间】:2017-06-05 19:11:18
【问题描述】:

我运行此代码并遇到时间超出错误,它实现了对数组的循环右移,给定数组大小、元素和移位宽度,将不胜感激为什么这会导致执行问题的一些帮助,我是新手:)

#include<stdio.h>
void main()
{
int n,i;

//array size input
scanf("%d",&n);
int a[n];

//array elements input
for(i=0;i<n;i++)
{
    scanf("%d",&a[i]);
}

// shift amount input
int s,temp;
scanf("%d",&s);

//single right shift for S number of times
for(i=0;i<s;i++)
{
    temp=a[n-1];
    for(i=n-1;i>0;i--)
    a[i]=a[i-1];
    a[0]=temp;
}

//Output of shifted array
for(i=0;i<n;i++)
{
    printf("%d\n",a[i]);
}
}

【问题讨论】:

  • 请注意intmain() 的唯一标准返回类型。
  • 可能与嵌套的for 循环有关。寻找更有效的方法。
  • 您对内部和外部嵌套的for 循环使用相同的索引变量i
  • 感谢您的帮助,更改变量名后有效

标签: c arrays error-handling


【解决方案1】:

s 嵌套循环需要进行主要更改,因为您在外部和内部循环中都使用了相同的变量。

更正如下:
现场演示http://ideone.com/DaokVy

#include <stdio.h>


int main()  // use properly
{
int n,i;

//array size input
scanf("%d",&n);
int a[100];    //edit

//array elements input
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}

// shift amount input
int s,temp,j;
scanf("%d",&s);


for(i=0;i<s;i++)
{
temp=a[n-1];

for(j=n-1;j>0;j--) // use different variable here
  a[j]=a[j-1];

a[0]=temp;
}

//Output of shifted array
for(i=0;i<n;i++)
{
printf("%d\n",a[i]);
}

return  0; // exit success
}

【讨论】:

  • @Recurse 支持并接受如果您觉得这有帮助。谢谢
猜你喜欢
  • 2021-12-31
  • 2021-01-08
  • 1970-01-01
  • 1970-01-01
  • 2013-02-22
  • 1970-01-01
  • 2018-10-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多