📜  交换两个数字的C程序

📅  最后修改于: 2021-05-31 20:33:56             🧑  作者: Mango

给定两个数字,编写一个C程序来交换给定的数字。

Input : x = 10, y = 20;
Output : x = 20, y = 10

Input : x = 200, y = 100
Output : x = 100, y = 200

这个想法很简单

  1. 将x分配给温度变量:temp = x
  2. 将y分配给x:x = y
  3. 将温度分配给y:y =温度

让我们以一个例子来理解。

// C program to swap two variables
#include 
  
int main()
{
    int x, y;
    printf("Enter Value of x ");
    scanf("%d", &x);
    printf("\nEnter Value of y ");
    scanf("%d", &y);
  
    int temp = x;
    x = y;
    y = temp;
  
    printf("\nAfter Swapping: x = %d, y = %d", x, y);
    return 0;
}

输出:

Enter Value of x 12

Enter Value of y 14

After Swapping: x = 14, y = 12 

如何编写函数进行交换?
由于我们希望main函数的局部变量可以通过swap函数进行修改,因此我们必须在C语言中使用指针。

// C program to swap two variables using a 
// user defined swap()
#include 
  
// This function swaps values pointed by xp and yp
void swap(int *xp, int *yp)
{
    int temp = *xp;
    *xp = *yp;
    *yp = temp;
}
  
int main()
{
    int x, y;
    printf("Enter Value of x ");
    scanf("%d", &x);
    printf("\nEnter Value of y ");
    scanf("%d", &y);
    swap(&x, &y);
    printf("\nAfter Swapping: x = %d, y = %d", x, y);
    return 0;
}

输出:

Enter Value of x 12

Enter Value of y 14

After Swapping: x = 14, y = 12 

用C++怎么做?
在C++中,我们也可以使用引用。

// C++ program to swap two variables using a 
// user defined swap()
#include 
  
// This function swaps values referred by 
// x and y,
void swap(int &x, int &y)
{
    int temp = x;
    x = y;
    y = temp;
}
  
int main()
{
    int x, y;
    printf("Enter Value of x ");
    scanf("%d", &x);
    printf("\nEnter Value of y ");
    scanf("%d", &y);
    swap(x, y);
    printf("\nAfter Swapping: x = %d, y = %d", x, y);
    return 0;
}

输出:

Enter Value of x 12

Enter Value of y 14

After Swapping: x = 14, y = 12 

有图书馆函数吗?
我们也可以使用C++库交换函数。

// C++ program to swap two variables using a 
// user defined swap()
#include 
using namespace std;
  
int main()
{
    int x, y;
    printf("Enter Value of x ");
    scanf("%d", &x);
    printf("\nEnter Value of y ");
    scanf("%d", &y);
    swap(x, y);
    printf("\nAfter Swapping: x = %d, y = %d", x, y);
    return 0;
}

输出:

Enter Value of x 12

Enter Value of y 14

After Swapping: x = 14, y = 12 


如何在不使用临时变量的情况下进行交换?