- 编写程序,从键盘输入三个整数 a,b,c,将 a 的值赋给 b,b 的值赋给 c,c 的值赋给 a。
输出改变后的 a,b,c 的值。(10 分)
#include <iostream>
using namespace std;
void swap(int &a,int &b)
{
int t;
t=a;
a=b;
b=t;
}
void swap3(int &a,int &b,int &c)
{
swap(a,c);
swap(b,c);
}
int main()
{
int a,b,c;
cin>>a>>b>>c;
swap3(a,b,c);
cout<<a<<" "<<b<<" "<<c<<endl;
return 0;
}
- 编写函数用辗转相除法求最大公因子,并将其改写成递归函数。(10 分)
#include <iostream>
using namespace std;
int fun(int m,int n){
if(m%n==0)
{
return n;
}
else
{
int mod=m%n;
m=n;
n=mod;
fun(m,n);
}
}
int main()
{
int m,n;
cin>>m>>n;
if(m<n)
{
int t=m;
m=n;
n=t;
}
cout<<fun(m,n);
return 0;
}
- 定义一个基类 FIGURE,在基类中定义纯虚函数 double get_area( );获得平面图形的面积
(提示:可在 FIGURE 类中定义数据成员 double x_size, y_size;)。另外定义派生类 TRIANGLE
(三角形)类,RECTANGLE(矩形)类,CIRCLE(圆形)类,在三个派生类中重新定义
get_area 函数并实现。
#include <iostream>
using namespace std;
class FIGURE{
public:
FIGURE(int x,int y)
{
x_size=x;
y_size=y;
}
double GetX(){
return x_size;
}
double GetY(){
return y_size;
}
virtual double get_area()=0;
private:
double x_size, y_size;
};
class TRIANGLE:public FIGURE{
public:
TRIANGLE(double w,double h):FIGURE(w,h){}
double get_area(){
return GetX()*GetY()/2;
}
};
class CIRCLE:public FIGURE{
public:
CIRCLE(double x,double y,double r):FIGURE(x,y){
this->r=r;
}
double get_area(){
return 3.14*r*r;
}
private:
double r;
};
class RECTANGLE:public FIGURE{
public:
RECTANGLE(double w,double h):FIGURE(w,h){}
double get_area(){
return GetX()*GetY();
}
};
void show(FIGURE *f){
cout<<"面积为"<<f->get_area()<<endl;
}
int main()
{
TRIANGLE t(1,2);
CIRCLE c(1,1,1);
RECTANGLE r(1,2);
FIGURE *f;
f=&t;
show(f);
f=&c;
show(f);
f=&r;
show(f);
return 0;
}