对于阵列时间超过无限循环的C的循环右移?

时间:2017-01-20 17:56:52

标签: c arrays error-handling

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

#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]);
}
}

1 个答案:

答案 0 :(得分:0)

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
}