![](/img/trans.png)
[英]How would I fix this if statement in C to get it working as intended?
[英]How can I fix the swapBack function to get the result I intended?
我正在尝试实现交换回 function,它将值交换回原始 position。 这是我必须做的指令:
实现第二个交换 function, swapBack(int v[2]),它将向量 v = [x, y] 作为输入并交换其条目。 在上面的程序中包含新的 function 以交换 x 和 y 的值。
#include <stdio.h>
void swap(int *pX, int * pY){
int temp = *pX;
*pX = *pY;
*pY = temp;
}
void swapBack(int x, int y){
swap(&x,&y);
}
int main() {
int x = 10;
int y = 5;
swap(&x, &y);
printf("x = %d, y = %d\n", x, y);
swapBack(&x, &y);
printf("x = %d, y = %d\n", x, y);
return x + y;
}
但是,两个printf
产生相同的结果,我不知道如何解决它? 谢谢
您定义swapBack
错误。 它应该采用两个整数的数组(衰减为指针)。
这应该与您想要的有关:
void swapBack(int v[2])
{
int temp = v[0];
v[0] = v[1];
v[1] = temp;
}
一个测试这个的程序:
#include <stdio.h>
void swapBack(int v[2])
{
int temp = v[0];
v[0] = v[1];
v[1] = temp;
}
int main(void)
{
int v[2] = {10, 5};
printf("v[0] = %d, v[1] = %d\n", v[0], v[1]);
swapBack(v);
printf("v[0] = %d, v[1] = %d\n", v[0], v[1]);
printf("v[0] + v[1] = %d\n", v[0] + v[1]);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.