gpt4 book ai didi

C 程序 - 移动数组中的元素

转载 作者:太空宇宙 更新时间:2023-11-04 03:32:32 25 4
gpt4 key购买 nike

"编写一个程序,允许用户输入一个整数作为数组的大小。推荐使用Malloc。为数组的每个元素随机生成一个整数。接下来,创建一个函数来旋转数组。旋转的数组的意思是每个元素右移或左移一个索引,数组的最后一个元素也移到第一位"

示例:31 83 91

向哪个方向移动多少次?- 向左

您想轮类多少次? 2

最终结果:91 31 83

目前我的代码。它没有移动。

#include <stdio.h>
#include <stdlib.h>

int main(){

int i, temp, swapped;
int SlotNumber;
int *ptr;
char direction;
int ShiftAmount;

printf("How many slots would you like in your array?\n");
scanf("%d", &SlotNumber);
for(i=0;i<SlotNumber;i++){
printf("%d \t", rand());
}
ptr = (int *)malloc(SlotNumber*sizeof(int));

printf("\nWhich direction would you like to shift it to? R/L?\n");
scanf(" %c", &direction);
printf("\nHow many times would you like to shift?\n");
scanf("%d", &ShiftAmount);

if((direction=='R')||(direction=='r')){
while(1){
swapped = 0;
for(i=0;i<ptr+1;i++){
if(ptr[1]>ptr[i+ShiftAmount]){
int temp = ptr[i];
ptr[i] = ptr[i+ShiftAmount];
ptr[i+ShiftAmount] =temp;
swapped = 1;
}
}
if(swapped == 0);
break;
}
}
printf("\nNewList\n");
for(i=0;i<ptr;i++){
printf("%d \t",ptr[i]);
}

return 0;
}

最佳答案

您的代码几乎没有问题。这是左移的改进解决方案,我留给你右移。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>


int main()
{

int i, j;
int SlotNumber;
int *ptr;
int ShiftAmount;
int temp;

srand(time(NULL));

printf("How many slots would you like in your array?\n");
scanf("%d", &SlotNumber);

ptr = malloc(SlotNumber*sizeof(int));

// Fill array with random numbers
for(i=0;i < SlotNumber; i++)
{
ptr[i]=rand();
printf("%d \t",ptr[i]);

}

printf("\nHow many times would you like to shift?\n");
scanf("%d", &ShiftAmount);


for(i=0; i < ShiftAmount; i++)
{
temp = ptr[0];
for(j=0;j < SlotNumber - 1;j++)
{
ptr[j] = ptr[j+1];
}
ptr[SlotNumber - 1]=temp;
}

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

free(ptr);

return 0;
}

关于C 程序 - 移动数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35233850/

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