1
#include <stdio.h>
#include <conio.h>

int main()
{
   int array[100], num1, c, n, num2;

   printf("Enter number of elements in array\n");
   scanf("%d", &n);

   printf("Enter %d elements\n", n);

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

   printf("Enter the number to swap\n");
   scanf("%d", &num1);

   printf("Enter the number to swap with\n");
   scanf("%d", &num2);

    printf("%d is swap place with %d.\n", num1, num2);


    for (c = 0; c < n; c++)
   {
   if (array[c] == num1)
   {
    array[c] = num2;
   }
   else if (array[c] == num2)
   {
    array[c] = num1;
   }
  }

  printf("The new output will be\n");

        getch();       
        return 0;
 }

嗨,我正在执行我的代码的一半,但我不知道如何继续。我正在编写代码以交换列表中的数字。有人可以帮帮我吗?

输入数组中的元素个数:5 输入 5 个元素 2 4 6 8 0 输入第一个要交换的数字:8 输入要交换的第二个数字:2 8 是与 2 交换的位置。输出将是:8 4 6 2 0

我如何输入-1来结束程序?示例:输入数组中的元素数:-1 输出:结束程序。

4

2 回答 2

0

只要没有进一步的说明,您只需遍历您的数组,并更改每次出现的8to 2,反之亦然。

int i;

for (i = 0; i < n; i++)
{
  if (array[i] == num1)
  {
    array[i] = num2;
  }
  else if (array[i] == num2)
  {
    array[i] = num1;
  }
}
于 2013-01-23T16:13:00.613 回答
0

您需要遍历数组以找到第一个和第二个数字的位置并交换它们

于 2013-01-23T16:13:48.903 回答