C++ variable exchange (third variable exchange method and summation method)

Description of the problem: There are positive integers a and b, input the values ​​of a and b, and make the output result exchange the values ​​of a and b (make the value of a equal to b, and the value of b equal to a)

Solution 1: The third variable exchange method

The third variable exchange method is to create a new auxiliary variable. Since directly assigning a to b will make a=b, then the value of b actually does not change when the code b=a is executed again, so create a new auxiliary variable c, which will be a is assigned to c, at this time c=a, then b is assigned to a, at this time a=b, and finally the operation of assigning c to b is performed, because c=a, so the original a is assigned to b ,code show as below:

#include<iostream>
using namespace std;
int main(){
    int a,b,c;
    cin>>a>>b;
    c = a;//将a赋值给c
    a = b;//将b赋值给a
    b = c;//将c赋值给b
    cout<<a<<" "<<b;//输出结果
    return 0;
}

Solution 2: Summation method

The summation method refers to assigning a+b to a, and the subsequent operations are as follows:

#include<iostream>
using namespace std;
int main(){
    int a,b;
    cin>>a>>b;
    a = a + b;//使a等于a+b
    b = a - b;//因为此时a=a+b,所以用a+b-b就等于原来的a,即将原来的a赋值给b
    a = a - b;//因为此时a=a+b,b等于原来的a,所以用a+b-a就等于b,即将原来的b赋值给a
    return 0;
}

The above is the knowledge sharing~

Remember to like it!

Guess you like

Origin blog.csdn.net/pyz258/article/details/129109006