Many people may think that this programming problem is very simple, only need to set an intermediate variable, and then by assigning a value to complete the exchange of two values of the content.
Let's take a closer look at this simple question today:
The most basic code is as follows:
#include <stdio.h>intMain () {intA =1, B =2, T; printf ("a=%d,b=%d\n", A, b); T=A; a=b; b=t; printf ("a=%d,b=%d\n", A, b); System ("Pause"); return 0;}
But what if the title requires not to use intermediate variables to complete the above requirements?
Then we need to think about how to exchange operations using only the given variables a and b.
We can make a=a+b, when a is already the value of a and the value of B.
Once again, the b=a-b can be exchanged for B-values.
At this time A=a-b, the exchange of a value is completed.
The code is as follows:
#include <stdio.h>intMain () {intA =1, B =2; printf ("before:a=%d b=%d\n", A, b); A= A +b; b= A-b; A= A-b; printf ("after:a=%d b=%d\n", A, b); System ("Pause"); return 0;}
However, after repeated consideration, we will find that the algorithm actually has some problems.
That is, when a and B numbers are large, overflow occurs, exceeding the integer range of int.
We can then choose a third algorithm for programming, using XOR or operator programming.
The code is as follows:
#include <stdio.h>intMain () {intA =1; intb =2; printf ("before:a=%d b=%d\n", A, b); A= a^b; b= a^b; A= a^b; printf ("after:a=%d b=%d\n", A, b); System ("Pause"); return 0;}
Finally, we enclose the results of the program experiment:
Implemented in C: Swaps the contents of two values.