#include <stdio.h> void main() { void swap (int a, int b); int a=1, b=2; swap (b, a); printf ("a=%d, b=%d\n" , a, b); } void swap (int a,int b) { printf (" a=%d, b=%d\n", a , b) ; a=3; b=4;}
时间: 2024-01-23 22:02:38 浏览: 19
这段代码的输出结果是:
```
a=1, b=2
a=2, b=1
```
这是因为在主函数中定义了变量a和b,并将它们的值分别设为1和2。然后调用了swap函数,并将b和a作为参数传递给了该函数。在swap函数中,a和b的值被输出,并被分别设为3和4。但是这个修改只是在swap函数内部发生的,不会影响到主函数中的a和b变量。因此,主函数中的a和b仍然分别为1和2,最终输出结果就是a=1, b=2。
相关问题
#include <stdio.h> void swap( int *pl,int *p2) { int p; p=*pl; *p1=*p2; *p2=p; } void main() { int a,b; scanf(" %d%d ",&a, &b);
这段代码存在几个问题:
1. 函数 swap 的参数名应该是 p1 和 p2,而非 pl 和 p2。
2. 函数 swap 中的变量名 p 和参数名 p2 重复。
3. 函数 swap 中交换两个变量的语句有误,应该是 *p1 = *p2; *p2 = p;。
4. 函数 main 中没有调用 swap 函数。
5. scanf 函数中的格式化字符串多了一个空格,应该改为 scanf("%d%d", &a, &b);。
修正后的代码如下:
```c
#include <stdio.h>
void swap(int *p1, int *p2) {
int tmp = *p1;
*p1 = *p2;
*p2 = tmp;
}
int main() {
int a, b;
scanf("%d%d", &a, &b);
swap(&a, &b);
printf("a = %d, b = %d\n", a, b);
return 0;
}
```
输入例如:
```
1 2
```
输出结果为:
```
a = 2, b = 1
```
#include <stdio.h> #include <stdlib.h> void Swap(int x, int y){ int tmp; tmp = x; x = y; y = tmp; } int main(){ int num1 = 10; int num2 = 20; Swap(num1,num2); printf("num1 = %d,num2 = %d\n",num1,num2); } 为什么这个程序输出结果不交换,原因及多种正确代码表示
这个程序输出结果不交换的原因是因为在 Swap 函数中,传入的参数是按值传递(pass by value),也就是说,在函数内部修改的是传入参数的副本,而不是传入参数本身。因此,函数内部的交换操作并不会影响到调用函数时传入的参数。要解决这个问题,可以使用指针或者引用作为函数参数,这样就可以修改传入参数的值。以下是两种正确的代码表示:
使用指针:
```c
#include <stdio.h>
#include <stdlib.h>
void Swap(int *x, int *y){
int tmp;
tmp = *x;
*x = *y;
*y = tmp;
}
int main(){
int num1 = 10;
int num2 = 20;
Swap(&num1,&num2);
printf("num1 = %d,num2 = %d\n",num1,num2);
}
```
使用引用:
```c
#include <stdio.h>
#include <stdlib.h>
void Swap(int &x, int &y){
int tmp;
tmp = x;
x = y;
y = tmp;
}
int main(){
int num1 = 10;
int num2 = 20;
Swap(num1,num2);
printf("num1 = %d,num2 = %d\n",num1,num2);
}
```
在以上两种情况下,传入的参数都可以被正确的交换。
相关推荐
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)