在不使用第三个变量的情况下交换两个变量的值——数组

Swapping values of two variables without using a third one- Array

本文关键字:变量 数组 交换 两个 情况下 三个      更新时间:2023-10-16

我正在编写一个程序,它接受用户输入来确定一对数字,并交换用户输入的所有对的值。

例如:

用户想输入3对,那么他将输入3后跟成对:

31 23 45 6

输出:

2 14个36 5

我的程序给出了正确的输出,但不是一次取所有对,而是一个接一个地取它们并给出输出。我有一个模糊的想法,这可以通过使用数组来解决,但不确定如何。请帮助。

下面是我的代码:
#include <stdio.h>
int main()
{
    int x, y, p, i;
   //int a [100], b[100];
    printf ("How many pairs?n");
    scanf ("%d", &p);
    for(i=1; i<=p; i++)
    {
       printf ("Enter two values:n");
       scanf("%d %d",&x,&y);
       x = x + y;  
       y = x - y;  
       x = x - y;
      //a[i]=x;
      //b[i]=y;

      printf("n");
      printf("After Swapping: x = %d, y = %dn", x, y);
     }
     return 0;
}

当前输出如下:

有几对?2

输入两个值:2 3

交换x= 3和y=2后

输入两个值:4 5

交换x= 5和y=4后。我想让它把所有4个值一起显示输出

我想,你正在寻找这样的东西(你只需要一个数组;您可以直接存储交换顺序的值):

for(i=0; i<p; i++) {
    scanf("%d %d",&x,&y);
    a[2*i+1]=x;
    a[2*i]=y;
}
for(i=0; i<2*p; i++) {
    printf("%d ", a[i]);
}
printf("n");

您可以将它们存储在数组中(就像您在某些注释代码中尝试的那样),然后逐个交换它们。

#include <stdio.h>
int main()
{
    int x, y, p, i;
    printf ("How many pairs?n");
    scanf ("%d", &p);
    int a[p],b[p];
    for(i=0; i<p; i++)
    {
        printf ("Enter values for pair %d:n", i+1);
        scanf("%d %d",&a[i],&b[i]);
    }
    for(i=0; i<p; i++)
    {
        x = a[i];
        y=b[i];
        x = x + y;  
        y = x - y;  
        x = x - y;
        printf("Pair %d After Swapping: x = %d, y = %dn", i+1, x, y);
    }
     return 0;
}

试试:http://goo.gl/5JJ7i3

我假设你在C上工作,所以我只使用C头。一种方法是首先找出有多少对,动态地分配空间,用输入的整数填充数组,交换它们,然后打印它们。

#include <stdio.h>
#include <stdlib.h>
int main()
{
    printf("Enter numbers: ");
    /* Get the number of pairs. */
    int prs;
    scanf_s("%i",&prs);
    /* Create a dynamic array. */
    prs*=2;
    int *A = (int*) malloc(prs*sizeof(int));
    /* Read the integers into the array. */
    int i=0;
    for(;i!=prs;scanf_s("%i",&A[i++]));
    /* Swap. */
    int j=0;
    for(;j!=prs;j+=2)
    {
        int tmp = A[j];
        A[j] = A[j+1];
        A[j+1] = tmp;
    }
    /* Print. */
    for(i=0;i!=j;printf("%i ",A[i++]));
    printf("n");
}

干杯!如果你对真正变得优秀感兴趣,试试这本书。

既然您已经添加了一个c++标记,我将建议一个简单的STL解决方案:

#include <iostream>
#include <vector>
int main(){
  std::vector<std::pair<int,int>> Vec;
  std::pair<int,int> Pr;
  int n;
  std::cin>>n;  //no. of pairs
  while(n--){
    std::cin>>Pr.second>>Pr.first;  //pair of elements stored in swapped locations
    Vec.push_back(Pr);
  }
  for(auto element : Vec){
    std::cout<<element.first<<" "<<element.second<<" ";
  }
  return 0;
}