(1)指针的基本操作(1)
下面的程序,输入10 100和100 10,均可以输出max=100 min=10,请补充完整程序
/*
* Copyright (c) 2014,烟台大学计算机学院
* All right reserved.
* 作者:邵帅
* 文件:temp.cpp
* 完成时间:2014年12月3日
* 版本号:v1.0
*/
#include <iostream>
using namespace std;
int main( )
{
int *p1,*p2,a,b,t;
cin>>a>>b;
p1=&a;
p2=&b;
if (*p1<*p2)
{
t=*p1;
*p1=*p2;
*p2=t;
}
cout<<"Max="<<a<<" Min="<<b<<endl;
return 0;
}
运行结果:
(2)指针的基本操作(2)
/*
* Copyright (c) 2014,烟台大学计算机学院
* All right reserved.
* 作者:邵帅
* 文件:temp.cpp
* 完成时间:2014年12月3日
* 版本号:v1.0
*/
#include <iostream>
using namespace std;
int main( )
{
int *p1,*p2,t;
p1=new int;
p2=new int;
cin>>*p1>>*p2;
if (*p1<*p2)
{
t=*p1;
*p1=*p2;
*p2=t;
}
cout<<"Max="<<*p1<<" Min="<<*p2<<endl;
delete p1;
delete p2;
return 0;
}
运行结果:
(3)指针当形参
下面的程序将调用函数进行变量的交换,请设计出交换的函数。/*
* Copyright (c) 2014,烟台大学计算机学院
* All right reserved.
* 作者:邵帅
* 文件:temp.cpp
* 完成时间:2014年12月3日
* 版本号:v1.0
*/
#include <iostream>
using namespace std;
void jiaohuan(int *p1, int *p2);
int main( )
{
int a,b;
cin>>a>>b;
jiaohuan(&a,&b);
cout<<a<<" "<<b<<endl;
return 0;
}
void jiaohuan(int *p1,int *p2)
{
int t;
t=*p1;
*p1=*p2;
*p2=t;
}
运行结果:
(4)两数和与差(用参数带回结果)
下面的程序,输入两个整数,调用函数ast后,输出了两数之和及两数之差。/*
* Copyright (c) 2014,烟台大学计算机学院
* All right reserved.
* 作者:邵帅
* 文件:temp.cpp
* 完成时间:2014年12月3日
* 版本号:v1.0
*/
#include <iostream>
using namespace std;
void ast(int x,int y,int *cp,int *dp)
{
*cp=x+y;
*dp=x-y;
}
int main()
{
int a,b,c,d;
cin>>a>>b;
ast(a,b,&c,&d);
cout<<c<<" "<<d<<endl;
return 0;
}
运行结果:
@ Mayuko