![](/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.