Méthode de permutation des valeurs de deux variables sans utiliser la troisième variable

1. Utilisez la définition de macro:

# définir le SWAP (X, Y) (X ) + = (Y); (Y) = (X) - (Y); (X) = (X) - (Y);

2. Utilisez l'opérateur XOR

int x = 21 ;
int y = 12 ; 

x ^ = y; 
y ^ = x; 
x ^ = y;

 

#include <stdio.h> 
#include <stdlib.h> int main ( int argn, char * argv []) 
{ int i = 0 ;
    int j = 0 ; if ((++ i> 0 ) || (++ j> 0 )) 
    { 
        printf ( " i =% d \ n " , i); 
        printf ( " j =% d \ n " , j); 
    } int x = 21 ;
    int y = 12 ; 
    x ^ =


    
    
    

    
y; 
    y ^ = x; 
    x ^ = y; 

    printf ( " ici x =% d \ n " , x); 
    printf ( " ici y =% d \ n " , y); 

    SWAP (x, y); 

    printf ( " ici x =% d \ n " , x); 
    printf ( " ici y =% d \ n " , y); 
    
    retourner  0 ; 
}

 

Je suppose que tu aimes

Origine www.cnblogs.com/weiyouqing/p/12689264.html
conseillé
Classement