交换两个变量的值(4种方法)

来源:互联网 发布:购买自己的淘宝客链接 编辑:程序博客网 时间:2024/09/21 08:58

第一种,最简单最常用的。

#include<stdio.h>int main(){    int a=1,b=2;    int c;    c=a;    a=b;    b=c;        printf("%d,%d\n",a,b);    return 0;}

第二种,使用位运算。
#include<stdio.h>int main(){    int a=1,b=2;    a=a^b;    b=b^a;    a=a^b;    return 0;<pre name="code" class="cpp">    printf("%d,%d\n",a,b);
}

注: 0^X=X

      a=X^Y         

      b=X^Y^Y=X

      a=X^Y^X=Y

第三种,使用指针,调用函数。

#include<stdio.h>void exchange(int *a,int *b){    int c;    c=*a;    *a=*b;    *b=c;}int main( ){    int a=1,b=2;    int *p1,*p2;    p1=&a;    p2=&b;    exchange(p1,p2);      printf("%d,%d\n",a,b);      return 0; }
第四种,该方法是转载的,原文地址:点击打开链接

#include<stdio.h>int main (){//int a,b;int a=1,b=2; //printf("please enter two numbers.\n",);//scanf("%d,%d",&a,&b);a=b-a;b=b-a;a=b+a;printf("%d,%d\n",a,b);return 0;} 

还有什么方法,欢迎大家补充!谢谢









0 0
原创粉丝点击