C程序交换两个数字

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

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

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

图片[1]-C程序交换两个数字-yiteyi-C++库

这个想法很简单

  1. 将x分配给一个临时变量:temp=x
  2. 将y分配给x:x=y
  3. 将temp分配给y:y=temp

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

x=100,y=200

第1行之后:温度=x 温度=100

第2行之后:x=y x=200

第3行之后:y=温度 y=100

// C program to swap two variables
#include <stdio.h>
int main()
{
int x, y;
printf ( "Enter Value of x " );
scanf ( "%d" , &x);
printf ( "Enter Value of y " );
scanf ( "%d" , &y);
int temp = x;
x = y;
y = temp;
printf ( "After 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的局部变量,因此必须使用 C语言中的指针 .

// C program to swap two variables using a
// user defined swap()
#include <stdio.h>
// 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 ( "Enter Value of y " );
scanf ( "%d" , &y);
swap(&x, &y);
printf ( "After 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 <stdio.h>
// 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 ( "Enter Value of y " );
scanf ( "%d" , &y);
swap(x, y);
printf ( "After 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 <bits/stdc++.h>
using namespace std;
int main()
{
int x, y;
printf ( "Enter Value of x " );
scanf ( "%d" , &x);
printf ( "Enter Value of y " );
scanf ( "%d" , &y);
swap(x, y);
printf ( "After 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 

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

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享