taiyang2014

C语言中交换两个数值的方法

 //方法1
    int  one = 1;
    int two = 2;
    int temp = 0;
    temp = one;
    one = two;
    two = temp;
    printf("one = %d\n", one);
    printf("two = %d\n", two);
    
        //方法2
    int a1 = 5;
    int a2 = 8;
    a1 = a2 - a1;
    a2 = a2 - a1;
    a1 = a1 + a2;
    printf("a1 = %d\n", a1);
    printf("a2 = %d\n", a2);
        //方法3
    
    int c = 10, d = 20;
    c = c ^ d;
    d = d ^ c;
    c = c ^ d;
    printf("c = %d\n", c);
    printf("d = %d\n", d);
 
        //方法4
    int e = 10, f = 20;
    int *g = &e, *h = &f;
    int tep = *g;
    *g = *h;
    *h = tep;
    printf("e = %d\n", e);
    printf("f = %d\n", f);

 

posted on 2015-03-01 21:15  taiyang2014  阅读(593)  评论(0编辑  收藏  举报

导航