我刚刚实现了我的交换功能,但它没有打印任何东西。你知道为什么 printf 行不执行吗?
#include <stdio.h>
int swap(int x, int y) {
scanf("%d", &x);
printf("%d, x is",x);
scanf("%d", &y);
int temp = x;
x = y;
y = temp;
printf("After Swapping: x = %d, y = %d", x, y);
return 0;
}
int main() {
swap(6,5);
}
最佳答案
您不应在 swap
函数内接受用户输入。它的目的应该是只交换两个整数。您可以将 scanf
语句移动到 main
函数。
#include <stdio.h>
int swap(int x, int y){
int temp = x;
x = y;
y = temp;
printf("After Swapping in swap function: x = %d, y = %d", x, y);
return 0;
}
int main(void){
int x, y;
scanf("%d", &x);
printf("%d, x is", x);
scanf("%d", &y);
printf("%d, y is", y);
swap(x, y);
printf("After Swapping in main function: x = %d, y = %d", x, y);
}
但是上面的代码有一个大问题。尽管 swap
函数在交换时打印传递的整数,但事实是 main
中的 x
和 y
保持不受影响。
在这种情况下,要让它工作,使用指针会很有帮助
void swap(int *ptrx, int *ptry){
int temp = *ptrx;
*ptrx = *ptry;
*ptry = temp;
}
在 main
函数中调用 swap
作为 swap(&x, &y);
关于c - 在 C 中交换 - 打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54960517/