编写程序交换任意两个整数
时间: 2023-03-25 16:02:16 浏览: 96
可以使用一个临时变量来实现交换两个整数的值,具体代码如下:
```c
#include <stdio.h>
int main() {
int a = 10, b = 20;
int temp;
printf("交换前:a=%d, b=%d\n", a, b);
temp = a;
a = b;
b = temp;
printf("交换后:a=%d, b=%d\n", a, b);
return ;
}
```
输出结果为:
```
交换前:a=10, b=20
交换后:a=20, b=10
```
相关问题
编写程序,利用指针交换两个数据
很好,我可以回答这个问题。以下是一个简单的程序示例,可以通过指针交换两个整数:
```c++
#include <iostream>
using namespace std;
//函数声明
void swap(int* x, int* y);
//主函数
int main()
{
int a = 5, b = 10;
cout << "交换前:" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
//调用swap函数交换a和b的值
swap(&a, &b);
cout << "交换后:" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}
//函数定义
void swap(int* x, int* y)
{
int temp = *x;
*x = *y;
*y = temp;
}
```
在这个程序中,swap函数接受两个整型指针作为参数,并且将它们指向的值进行交换。在主函数中,定义了两个整型变量a和b,并且在调用swap函数之前输出了它们的值,然后再调用swap函数,之后再次输出a和b的值,以发现它们已经被交换了。
希望这个示例可以对你有所帮助,如果你有任何其他问题,可以随时问我。
C语言编写程序从键盘输入任意两个整数,并交换他们的值输出
可以使用以下代码:
```c
#include <stdio.h>
int main() {
int num1, num2, temp;
printf("请输入两个整数:\n");
scanf("%d%d", &num1, &num2);
// 交换两个整数的值
temp = num1;
num1 = num2;
num2 = temp;
printf("交换后的值为:%d %d\n", num1, num2);
return 0;
}
```