gpt4 book ai didi

c - C 中的交换问题 [初学者]

转载 作者:行者123 更新时间:2023-11-30 20:50:53 27 4
gpt4 key购买 nike

我被要求在 2 个整数之间进行交换。

#include <stdio.h>
#include <stdlib.h>

void swaplol(int a, int b)
{
int tmp;
tmp = a;
a = b;
b = tmp;

printf("After the swap : a= %d, b=%d\n",a,b);

}

我不明白问题出在哪里。一切似乎都很好合成明智......

int main(void)
{
int a,b;
a = 666;
b = 998;

printf("Before the swap a = %d, b = %d\n",a,b);

swaplol(a,b);

return 0;
}

谢谢

最佳答案

您需要将整数的地址传递给交换函数,以便当交换值时,您可以在 main 中交换 a 和 b 值。因此,您必须更改 swaplol 函数以接受指针而不是整数。

#include <stdio.h>
#include <stdlib.h>

void swaplol(int *a, int *b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;

printf("After the swap : a= %d, b=%d\n",*a,*b);

}

int main(void) {
// your code goes here
int a,b;
a = 666;
b = 998;

printf("Before the swap a = %d, b = %d\n",a,b);

swaplol(&a,&b);
printf("After the swap : a= %d, b=%d\n",a,b);
return 0;
}

关于c - C 中的交换问题 [初学者],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37282450/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com