下面程序怎么改#include<stdio.h> void swap(int x,int y) ; void main(void) { int a,b; printf("请输入交换的数值:") ; scanf("%d%d",&a, &b); printf("交换前a=%d,b=%d\n",a,b); swap (&a, &b); printf("交换后a=%d,b=%d\n",a,b); } void swap(int *x, int *y) { int temp; temp=*x; *x=*y; *y=temp; }
时间: 2024-01-13 19:05:55 浏览: 25
这个程序需要改动的地方是 `void swap(int x,int y)` 这一行,因为 `swap` 函数需要接收两个指向整型变量的指针参数,而不是两个整型变量本身。因此,需要将其改成 `void swap(int *x, int *y)`,表示接收两个指向整型变量的指针参数。另外,`main` 函数的返回值应该是 `int` 类型,因此需要将 `void` 改成 `int`。修改后的代码如下所示:
```c
#include <stdio.h>
void swap(int *x, int *y);
int main(void) {
int a, b;
printf("请输入交换的数值: ");
scanf("%d%d", &a, &b);
printf("交换前a=%d,b=%d\n", a, b);
swap(&a, &b);
printf("交换后a=%d,b=%d\n", a, b);
return 0;
}
void swap(int *x, int *y) {
int temp;
temp = *x;
*x = *y;
*y = temp;
}
```
修改后的程序使用了指针来交换变量的值,可以正确地交换两个变量的值。
相关问题
#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);
}
```
在以上两种情况下,传入的参数都可以被正确的交换。
修正#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 的值已经被成功交换了。