簡體   English   中英

如何修復 swapBack function 以獲得我想要的結果?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM