【问题标题】:C Program - Shifting Elements in an arrayC 程序 - 移动数组中的元素
【发布时间】:2016-02-05 21:28:55
【问题描述】:

"编写一个程序,允许用户输入一个整数作为数组的大小。推荐使用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;
}

【问题讨论】:

  • 1) 你没有用任何东西填充 ptr 数组。 2)你只需要改变元素。您不关心它们的值是什么,因此没有理由检查一个元素的值是否大于另一个元素的值。但是,您确实需要检查新位置是否在数组的边界内,如果不在则采取适当的措施。
  • 文字说你必须移动1元素。然而,该示例询问用户他们想要移动“多少次”。所以本质上这是n元素的转变。移动n 元素是一个比移动1 更通用和更有趣的问题。那么,实际需要什么?换档1 还是换档n?还是需要通过1的连续轮班来实现n的轮班?

标签: c arrays


【解决方案1】:

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

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

【讨论】:

  • 谢谢。我添加了打印语句来询问用户移位方向,我也能够让它向右移位。
  • @EGTech 很高兴听到这个消息
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多