#include<iostream>
#include <string>
using namespace std;
int main(){
int *p1, *p2, *p, a, b;
cout << "please input a he b" << endl;
cin >> a >> b;
p1 = &a;
p2 = &b;
if (a < b)
{
p = p1;
p1 = p2;
p2 = p;
}
cout << "a=" << a << "b=" << b << endl;
cout << "max=" << *p1 << "min=" << *p2 << endl;
return 0;
}
方法二:使用指针作为函数参数
#include<iostream>
#include <string>
using namespace std;
int main(){
int a, b;
void swap(int *p1, int *p2);
int *pointer_1, *pointer_2;
cout << "请输入a和b的值:"<<endl;
cin >> a >> b ;
pointer_1 = &a;
pointer_2 = &b;
if (a < b)
swap(pointer_1, pointer_2);
cout << "a=" << a << "b=" << b << endl;
cout << "max=" << a << "min=" << b << endl;
return 0;
}
void swap(int*p1, int*p2)
{
int temp;
temp = *p1;
*p1 = *p2;
*p2 = temp;
}