交换2个数

来源:互联网 发布:omp算法 matlab 编辑:程序博客网 时间:2024/05/01 07:43

  交换两个数,分别用创建第三个变量,和不创建第三个变量的方法,以及用位运算实现.

交换俩个数,用第三个变量.

#include <stdio.h>#include <stdlib.h>int main(){    int a = 10;    int b = 20;    int temp = 0;    printf("a=%d b=%d\n", a, b);    temp = a;    a = b;    b = temp;    printf("a=%d b=%d\n", a, b);    system("pause");}

交换两个数,不用第三个变量.

#include <stdio.h>#include <stdlib.h>int main(){    int a = 10;    int b = 20;    printf("a=%d b=%d\n", a, b);    a = a + b;    b = a - b;    a = a - b;    printf("a=%d b=%d\n", a, b);    system("pause");}

交换两个数,用位运算

#include <stdio.h>#include <stdlib.h>int main(){    int a = 10;    int b = 20;    printf("a=%d b=%d\n", a, b);    a = a^b;    b = a^b;    a = a^b;    printf("a=%d b=%d\n", a, b);    system("pause");  return 0;}

用python实现

a = 10b = 20a,b =b,aprint a,b
原创粉丝点击