C language: four methods; two integers are exchanged (including the introduction of third-party variables and the absence of third-party variables)
Method 1: Program: # include <stdio. h> void swap (int * p1, int * p2) {int t = * p1; * p1 = * p2; * p2 = t;} int main () {int num1 = 2; int num2 = 4; int tmp = 0; printf ("num1 = % d \ n", num1 ); printf ("num2 = % d \ n", num2); swap (& num1, & num2); printf ("num1 = % d \ n", num1 ); printf ("num2 = % d \ n", num2); return 0;} result: num1 = 2num2 = 4num1 = 4num2 = 2 Press any key to continue Method 2: XOR program: # include <stdio. h> int main () {int num1 = 2; int num2 = 4; printf ("num1 = % d \ n", num1 ); printf ("num2 = % d \ n", num2); // num1 ^ num2; // 011 // 101 // 110 // The XOR method can exchange Integer Variables. For floating-point variables, num1 = num1 ^ num2 cannot be exchanged; num2 = num1 ^ num2; num1 = num1 ^ num2; printf ("num1 = % d \ n", num1); printf ("num2 = % d \ n", num2 ); return 0;} result: num1 = 2num2 = 4num1 = 4num2 = 2 Press any key to continue method 3: add or subtract program: # include <stdio. h> int main () {int num1 = 3; int num2 = 12; printf ("num1 = % d \ n", num1 ); printf ("num2 = % d \ n", num2); num1 = num1 + num2; num2 = num1-num2; num1 = num1-num2; // variable that can exchange integer and floating point values, however, loss of precision may occur when processing floating point models. printf ("num1 = % d \ n", num1); printf ("num2 = % d \ n", num2 ); return 0;} result: num1 = 3num2 = 12num1 = 12num2 = 3 Press any key to continue precision loss: Program: # include <stdio. h> int main () {float num1 = 3.123456; float num2 = 1234567.000000; printf ("num1 = % f \ n", num1 ); printf ("num2 = % f \ n", num2); num1 = num1 + num2; num2 = num1-num2; num1 = num1-num2; // variable that can exchange integer and floating point values, however, loss of precision may occur when processing floating point models. printf ("num1 = % f \ n", num1); printf ("num2 = % f \ n", num2 ); return 0;} error returned: num1 = 3.123456num2 = 1234567.000000num1 = 1234567.001544num2 = 3.123456 Press any key to continue is changed to double type, the range is increased, and the running result is correct: num1 = 3.123456num2 = 1234567.000000num1 = 1234567.000000num2 = 3.123456 Press any key to continue Method 4: multiplication and division program: # include <stdio. h> int main () {int num1 = 2; int num2 = 4; printf ("num1 = % d \ n", num1 ); printf ("num2 = % d \ n", num2); // The same as addition and subtraction, You can exchange variables of integer and floating point values, however, when processing the floating point type, the loss of precision may occur. num1 = num1 * num2; num2 = num1/num2; num1 = num1/num2; printf ("num1 = % d \ n", num1); printf ("num2 = % d \ n", num2); return 0 ;}result: num1 = 2num2 = 4num1 = 4num2 = 2