#include< stdio.h> void fun(int x, int y) { int t; t = x; x = y; y = t; } void main() { int a=1,b=2; fun (a,b); printf("%d,%d\n",a,b); }
时间: 2023-12-03 12:03:12 浏览: 138
这段代码的输出结果为“1,2”。
原因是调用函数fun时,传递的是a和b的拷贝,函数内部对x和y的操作不会影响到a和b的值。在函数fun中,x和y的值交换了,但是并没有改变a和b的值。
因此,函数结束后,a和b的值还是原来的值,分别为1和2。在main函数中,printf函数输出a和b的值,因此输出结果为“1,2”。
相关问题
#include<stdio.h> void fun(int *a, int *b) { int *t; t=a;a=b;b=t; } void main( ) { int x=3, y=4; fun(&x, &y); printf("%d, %d", x, y);
这段代码的作用是交换变量x和y的值。但是代码有一个小错误,main函数的返回值类型应该是int而不是void。
正确的代码应该是这样的:
```
#include <stdio.h>
void fun(int *a, int *b) {
int *t;
t = a;
a = b;
b = t;
}
int main() {
int x = 3, y = 4;
fun(&x, &y);
printf("%d, %d", x, y);
return 0;
}
```
运行结果会输出 "3, 4",因为指针变量a和b在fun函数内部交换了指向的地址,但是并没有改变x和y的值。如果想要交换x和y的值,可以修改fun函数的实现,如下所示:
```
void fun(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}
```
这样运行结果就会输出 "4, 3"。
#include<stdio.h> void fun(int* a, int* b) { int* t; t = a; a = b; b = t; } void main() { int x = 3, y = 4; fun(&x,&y); printf("%d,%d",x,y); }怎么交换x,y的值
可以在函数 fun 中改变指针所指向的变量的值,从而实现交换 x 和 y 的值。修改后的代码如下:
```
#include <stdio.h>
void fun(int* a,int* b){
int t;
t = *a;
*a = *b;
*b = t;
}
int main(){
int x = 3, y = 4;
fun(&x,&y);
printf("%d,%d",x,y);
return 0;
}
```
在 fun 函数中,我们通过操作指针所指向的变量,将变量 x 和 y 的值进行了交换。在 main 函数中,调用 fun 函数后,x 和 y 的值被交换,输出结果为 "4,3"。
相关推荐
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)