用的是VS2019,自己写的函数swap,函数swap没有改变实参的值是为什么,求解答.


#define _CRT_SECURE_NO_WARNINGS 1
#include

void swap(int x, int y)
{
    int temp;
    temp = x;
    x = y;
    y = temp;
}
int main()
{
    int a = 0;
    int b = 0;
    int c = 0;
    scanf("%d%d%d", &a, &b, &c);
    if (a > b)
        swap(a, b);
    if (a > c)
        swap(a, c);
    if (b > c)
        swap(b, c);
    printf("%d/%d", a, c);
    return 0;
}

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include <iostream>
//在前面用&,可以实现传参赋值!
void swap(int &x, int &y)
{
    int temp;
    temp = x;
    x = y;
    y = temp;
}
int main()
{
    int a;
    int b;
    int c;
    scanf("%d%d%d", &a, &b, &c);
    if (a > b)
        swap(a, b);
    if (a > c)
        swap(a, c);
    if (b > c)
        swap(b, c);
    printf("%d/%d", a, c);
    system("pause");
    return 0;
}

结果:

img

要传指针,你传值当然不会变

这就好像
int a=1;
int b=a;
b=2;
a的值不会变,是一样的道理
你想改变b的值的同时能够改变a的值,那b要定义成指针呀

传的并没有地址,所以不会改变他的值.你可以看看我写的这个代码


```c++
void swap01(int *p1,int *p2){
  int temp=*p1;
  *p1=*p2;
  *p2=temp;
}
swap(&a,&b);

```

swap(a,b)???
int a=1;
int b=a;
b=2;
你想改变b的值的同时能够改变a的值,那a,b要定义成指针呀!!!