gpt4 book ai didi

c - 程序移动数组中的元素(没有得到正确的输出)

转载 作者:行者123 更新时间:2023-11-30 21:36:53 25 4
gpt4 key购买 nike

我正在尝试为以下问题编写一个c程序:

Given a set of elements stored in an array and a number 'm', design an Algorithm and write the subsequent C program to perform cyclic right shift of the array by 'm' places. For example, if the elements are 12, 13, 16, 7, 10 and m =2 then the resultant set will be 7, 10, 12, 13, 16.

Input Format

Number of elements in the set: 'n'
element-1
element-2
...
element-n
value of 'm'

Output Format

Elements in the set after right shift by 'm' places

我编写的程序如下。

#include<stdio.h>

main()
{
int n,i,j,m,temp1,temp2;

printf("Given n:\n");
scanf("%d", &n);

int array[n];

printf("Enter the elements\n");

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

printf("Enter the shifts needed\n");
scanf("%d", &m);

for(i = 0;i<m;i++)
{
for(j=0;j<3;j++)
{
temp1 = array[j+1];
array[j+1] = array[j];
temp2 = array[j+2];
array[j+2] = temp1;
temp1 = array[j+3];
array[j+3] = temp2;
array[j] = temp1;
}
}

for (i = 0;i<n;i++)
{
printf("%d\t", array[i]);
}
}

输出与输入是同一组数字。

谁能帮我解决这个问题吗?

最佳答案

好吧,您可以创建一个新数组来放置数字,这样您就不会与临时值混淆并简化代码:

int new_array[n];

for(int i=0;i<n;i++){
new_array[(i+m)%n]=array[i];
}

关于c - 程序移动数组中的元素(没有得到正确的输出),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41792476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com