C language variable key exchange

We all know, C language swap two numbers, you can create a temporary variable as an intermediate value to complete the exchange, but with in-depth knowledge of learning, exchanging two numbers can also be achieved by other means, the following small series to explain a bit:

method one:

By creating a temporary variable to achieve the exchange as an intermediate value, as follows:

#include <stdio.h>
int main(){
    int x,y,temp;
    printf("请输入x和y的值: ");
    scanf("%d%d",&x,&y);
    temp=x;
    x=y;
    y=temp;
    printf("交换后的内容:x=%d,y=%d\n",x,y);
    return 0;	
}

Method Two:

By subtraction achieve the exchange of two numbers, as follows:

#include <stdio.h>
int main(){
    int x,y;
    printf("请输入x和y的值: ");
    scanf("%d%d",&x,&y);
    x=x+y;
    y=x-y;
    x=x-y;
    printf("交换后的内容:x=%d,y=%d\n",x,y);
    return 0;	
}

Method three:

By an exclusive OR process to achieve the exchange of two numbers, as follows:

Bit computing more details, please click: https://blog.csdn.net/qq_42680327/article/details/99862200

#include <stdio.h>
int main(){
    int x,y;
    printf("请输入x和y的值: ");
    scanf("%d%d",&x,&y);
    x=x^y;
    y=x^y;
    x=x^y;
    printf("交换后的内容:x=%d,y=%d\n",x,y);
    return 0;	
}

 

Published 153 original articles · won praise 215 · views 180 000 +

Guess you like

Origin blog.csdn.net/qq_42680327/article/details/104385211