码迷,mamicode.com
首页 > 其他好文 > 详细

在不申请第三方变量的情况下交换a和b

时间:2019-09-29 21:40:23      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:str   std   public   运算   void   src   swa   算数运算   div   

1、算数运算

a=a*b;b=a/b;a=a/b;

2、XOR运算

a和bxor运算两次还是 a

3、栈运算

stack<数据类型>s

4、程序运行 

 1 #include <iostream>
 2 #include<stdlib.h>
 3 #include<stack>//STL里重要的函数 
 4 using namespace std;
 5 /*void _stack(int x,int y){
 6 stack<int>s;
 7 s.push(x);
 8 s.push(y);
 9 x = s.top();
10 s.pop();
11 y = s.top();
12 s.pop();
13 cout << x << " " << y << endl;
14 }
15 void _arithmetic(int a, int b){
16 a = a*b;
17 b = a / b;
18 a = a / b;
19 cout << a << " " << b << endl;
20 }
21 void _xor(int a, int b){
22 a = a^b;
23 b = a^b;
24 a = a^b;
25 cout << a << " " << b << endl;
26 }*/
27 class _swap{
28 public:
29     void _valueab(){ cout << "请输入a和b的值:" << endl; cin >> a >> b; }
30     void _stack(){
31         stack<int>s;
32         s.push(a);
33         s.push(b);
34         a = s.top();
35         s.pop();
36         b = s.top();
37         s.pop();
38         cout << a << " " << b << endl;
39     }
40     void _arithmetic(){
41         a = a*b;
42         b = a / b;
43         a = a / b;
44         cout << a << " " << b << endl;
45     }
46     void _xor(){
47         a = a^b;
48         b = a^b;
49         a = a^b;
50         cout << a << " " << b << endl;
51     }
52 private:
53     int a, b;
54 };
55 int main(){//这里要用int,因为main函数会自带return 0,所以应该写int
56     _swap function;
57     function._valueab();
58     function._stack();
59     function._arithmetic();
60     function._xor();
61     system("pause");
62 }

5、运行结果

技术图片

 

在不申请第三方变量的情况下交换a和b

标签:str   std   public   运算   void   src   swa   算数运算   div   

原文地址:https://www.cnblogs.com/hehesunshine/p/11609916.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!