#include<stdio.h> void swap(int x,int y) { int t; t=x; x=y; y=t; } int main() { int a=3,b=7; swap(3,7); printf("a=%d\n",a); printf("b=%d\n",b); }
时间: 2023-12-02 17:05:18 浏览: 299
这段代码实现了一个交换两个变量值的函数 swap,但是在 main 函数中调用 swap 函数时,传入的参数是 3 和 7,而不是变量 a 和 b,因此交换的是 3 和 7,而不是 a 和 b,因此输出结果为:
```
a=3
b=7
```
交换函数应该改为传入指针或引用,才能实现对变量的交换。
相关问题
#include<stdio.h> void swap(int x,int y) { int t; t=x; x=y; y=t; } int main() { int a=3,b=7; swap(3,7); printf("a=%d\n",a); printf("b=%d\n",b); }想要交换ab的结果怎修改
要修改 swap 函数的参数为指针或引用,这样才能实现对变量的交换。改动后的代码如下:
```c
#include<stdio.h>
void swap(int *x, int *y) {
int t = *x;
*x = *y;
*y = t;
}
int main() {
int a = 3, b = 7;
swap(&a, &b);
printf("a=%d\n", a);
printf("b=%d\n", b);
return 0;
}
```
在 main 函数中调用 swap 函数时,传入的是变量 a 和 b 的地址,swap 函数中的参数也改为指针类型,通过指针操作实现对变量的交换。输出结果为:
```
a=7
b=3
```
可以看到,a 和 b 的值已经成功交换了。
修正#include<stdio.h> void swap(int a,int b) { int temp =a; a=b; b=temp; } int main() { int x=10,y=20 printf("before swap;x=%d,y=%d",x,y); swap (&x,&y); printf("after swap;x=%d,y=%d",x,y); return 0 }
修正后的代码如下,主要是将 swap 函数的参数改为指针类型,并在调用 swap 函数时传入 x 和 y 的地址:
```c
#include<stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 10, y = 20;
printf("before swap; x=%d, y=%d\n", x, y);
swap(&x, &y);
printf("after swap; x=%d, y=%d\n", x, y);
return 0;
}
```
输出结果为:
```
before swap; x=10, y=20
after swap; x=20, y=10
```
可以看到,经过 swap 函数交换后,x 和 y 的值已经被成功交换了。