重庆大学c++期末复习真题

#define e=2.7182818284
期末模拟
选择题
答案:CACBBCDCCA
分数 4
作者 刘骥
单位 重庆大学
下列程序代码,正确的输出结果是( )
int a=0xfe;
char b=062;
cout<<a<<“,”<<b<<endl;

A.
0xfe,062

B.
fe,62

C.
254,2

D.
254,62


2-2

分数 4
作者 刘骥
单位 重庆大学
下列代码能正确执行的是( )

A.
char a=‘C’;
const char& p=a;

B.
char a=‘C’;
char* const p;
p=&a;

C.
char a=‘C’;
const char& p;
p=a;

D.
char a=‘C’;
char& p;
p=a;


2-3

分数 4
作者 刘骥
单位 重庆大学
new和delete运算符正确的使用是( )

A.
int* p=new int[10];
delete p;

B.
int* p=new int(10);
delete []p;

C.
vector* v=new vector[10];
delete []v;

D.
int* a=new int[]{1,2,3,4};
delete []a;


2-4

分数 4
作者 刘骥
单位 重庆大学
下列哪个代码能够实现x和y值的交换( )

A.
void fun(int a,int b) {
int x = a;
a = b;
b = x;
}
int main() {
int x = 1, y = 2;
fun(&x, &y);
cout << x << “,”<<y << endl;
return 0;
}

B.
void fun(int* a,int* b) {
int x = *a;
*a = *b;
*b = x;
}
int main() {
int x = 1, y = 2;
fun(&x,&y);
cout << x << “,”<<y << endl;
return 0;
}

C.
void fun(int& a,int& b) {
int x = a;
a = b;
b = x;
}
int main() {
int x = 1, y = 2;
fun(&x, &y);
cout << x << “,”<<y << endl;
return 0;
}

D.
void fun(const int&a,const int&b) {
int x = a;
a = b;
b = x;
}
int main() {
int x = 1, y = 2;
fun(x, y);
cout << x << “,”<<y << endl;
return 0;
}


2-5

分数 4
作者 刘骥
单位 重庆大学
下面有一个结构体,对结构体的错误使用是( )
struct Book{
string name;
double price;
}

A.
Book b{“C++”,20};

B.
Book b;
b->name=“C++”;
b->price=20;

C.
Book *b=new Book[2];
b[0].name=“C++”;
b[0].price=20;

D.
Book *p=new Book();
p->name=“C++”;
p->price=20;


2-6

分数 4
作者 葛亮
单位 重庆大学
下列种类的函数中,哪一种不是类的成员函数?

A.
构造函数

B.
析构函数

C.
友元函数

D.
拷贝构造函数


2-7

分数 4
作者 葛亮
单位 重庆大学
父类Base和子类Derive的定义如下。请问在子类中,继承的父类成员f,x,y的访问控制权限分别是:
class Base
{
public:
void f();
protected:
int x;
private:
int y;
};

class Derive : protected Base
{
};

A.
public, protected, private

B.
public, public, public

C.
private, private, private

D.
protected, protected, private


2-8

分数 4
作者 葛亮
单位 重庆大学
当变量x的输入值是9时,下面程序的运行结果是:
#include
#include
using namespace std;
int main()
{
int x;
cin>>x;
try
{
cout<<“begin”<<endl;
if(x>100)
{
cout<<“1”<<endl;
throw string(“too big.”);
}
else
{
cout<<“x=”<<x<<endl;
}
cout<<“2”<<endl;
}
catch(string e)
{
cout<<“3:”<<e<<endl;
}
cout<<“end”<<endl;
return 0;
}

A.
begin
1
2
end

B.
begin
1
3: too big.
2
end

C.
begin
x=9
2
end

D.
begin
1
3: too big.
end


2-9

分数 4
作者 刘骥
单位 重庆大学
下列哪个代码不会调用对象的拷贝构造函数( )

A.
MyClass a;
MyClass b=a;

B.
MyClass a;
MyClass b(a);

C.
MyClass a;
MyClass& b=a;

D.
void f(MyClass obj)
{

}
MyClass a;
f(a);


2-10

分数 4
作者 刘骥
单位 重庆大学
根据下列类模板声明,正确初始化对象的方式是( )
template<typename T1, typename T2>
class MyClass{
private:
T1 x;
T2 y;
public:
MyClass(T1 _x, T2 _y):x(_x),y(_y){}
};

A.
MyClass<int,char> a(10,‘a’);

B.
MyClass a(10,‘a’);

C.
MyClass<int,char> a;

D.
MyClass a;

二、函数题:
6-1 类的定义(教师类Teacher)
分数 10
全屏浏览题目
切换布局
作者 刘骥
单位 重庆大学
本题要求定义一个教师类Teacher,数据成员包含姓名name和年龄age,类的声明见给出的代码,请给出类的完整实现,并通过测试程序。
类的声明:
class Teacher{
private:
string name;
int age;
public:
Teacher(string name,int age);
string getName() const;
int getAge() const ;
void setName(string name);
void setAge(int age);
};
测试程序:
#include
#include
using namespace std;
class Teacher{
private:
string name;
int age;
public:
Teacher(string name,int age);
string getName() const;
int getAge() const ;
void setName(string name);
void setAge(int age);
};

/* 请在这里填写答案 */

int main(){
Teacher a(“Wang”,20);
cout<<“name:”<<a.getName()<<endl;
cout<<“age:”<<a.getAge()<<endl;
a.setName(“Zhang”);
a.setAge(30);
cout<<“name:”<<a.getName()<<endl;
cout<<“age:”<<a.getAge()<<endl;
return 0;
}

1:答案
Teacher::Teacher(string name, int age) {
Teacher::name = name;
Teacher::age = age; //代码
}

string Teacher::getName() const {

return name;//代码

}

int Teacher::getAge() const {

return age;//代码

}

void Teacher::setName(string name) {
Teacher::name = name; //代码
}

void Teacher::setAge(int age) {
Teacher::age = age; //代码
}
6-2 加、不等和输入输出的运算符重载(2维向量Vec2)
维向量类Vec2,类的声明见给出的代码,请给出类的完整实现,并通过测试程序。类的声明包括如下内容:

  1. 数据成员,向量的第一维u和第二维v;
  2. u和v的访问函数;
  3. 构造函数;
  4. 加号、减号运算符重载(遵守二维向量的运算规则);
  5. 和!=运算符重载(遵守二维向量的运算规则)
    输入、输出运算符重载。class Vec2{
    private:
    double u;
    double v;
    public:
    Vec2(double u=0,double v=0);
    double getU() const;
    double getV() const;
    Vec2 operator+(const Vec2&b);
    friend Vec2 operator-(const Vec2&a,const Vec2&b);
    bool operator
    (const Vec2&b) const;
    friend bool operator!=(const Vec2&a,const Vec2&b);
    friend ostream&operator<<(ostream&os,const Vec2&c);
    friend istream&operator>>(istream&is,Vec2&c);
    };
    测试程序:
    #include
    using namespace std;
    class Vec2{
    private:
    double u;
    double v;
    public:
    Vec2(double u=0,double v=0);
    double getU() const;
    double getV() const;
    Vec2 operator+(const Vec2&b);
    friend Vec2 operator-(const Vec2&a,const Vec2&b);
    bool operator==(const Vec2&b) const;
    friend bool operator!=(const Vec2&a,const Vec2&b);
    friend ostream&operator<<(ostream&os,const Vec2&c);
    friend istream&operator>>(istream&is,Vec2&c);
    };
    double Vec2::getU() const
    {
    return u;
    }
    double Vec2::getV() const
    {
    return v;
    }
    Vec2 operator-(const Vec2&a,const Vec2&b){
    return Vec2(a.u-b.u,a.v-b.v);
    }
    bool Vec2::operator==(const Vec2&b) const{
    return ub.u&&vb.v;
    }
    /* 请在这里填写答案 */

int main(){
Vec2 a;
cin>>a;
cout<<"a: "<<a<<endl;
Vec2 b(3,4);
Vec2 c=a+b;
cout<<"c: "<<c<<endl;
Vec2 d=a-b;
cout<<"d: "<<d<<endl;
cout<<"aa: "<<(aa)<<endl;
cout<<"a!=a: "<<(a!=a)<<endl;
return 0;
}
测试程序的输入:
10 5
测试程序的输出:
a: u=10,v=5
c: u=13,v=9
d: u=7,v=1
a==a: 1
a!=a: 0
2、答案:
Vec2::Vec2(double u, double v ) {
Vec2::u = u;
Vec2::v = v;
}
Vec2 Vec2::operator+(const Vec2 &b) {

return Vec2(u + b.u, v + b.v);

}
bool operator!=(const Vec2 &a, const Vec2 &b) {
return a.u != b.u || a.v != b.v;
}

ostream &operator<<(ostream &os, const Vec2 &c) {
os << " u=" << c.u << “,v=” << c.v;
}

istream &operator>>(istream &is, Vec2 &c) {
is >> c.u >> c.v;
}
6-3 继承和多态(水果和香蕉)
分数 10
全屏浏览题目
切换布局
作者 刘骥
单位 重庆大学
请设计水果和香蕉类,并通过测试程序,具体要求如下:

  1. 水果(Fruit)是基类,成员包含:
    o 保护成员变量重量(weight,int类型)
    o 公有构造函数
    o 公有析构函数
    o 公有函数display
  2. 香蕉(Banana)从水果类公有继承,成员包含:
    o 私有成员变量产地(origin,string类型)
    o 公有构造函数
    o 公有析构函数
    o 公有函数display
    对应代码

3、答案:
class Fruit {
protected:
int weight;
public:
Fruit(int i) {
weight = i;
cout << “Fruit Constructor” << endl;
}
virtual ~Fruit() {
cout << “Fruit Destructor” << endl;
}
virtual void display() {
cout << “weight=” << weight << endl;
}
};

class Banana: public Fruit {
private:
string origin;
public :
Banana(string o, int i): Fruit(i) {
origin = o;
weight = i;
cout << “Banana Constructor” << endl;
}

	~Banana() {
		cout << "Banana Destructor" << endl;

	}
	void display() {
		cout << "origin=" << origin << ",weight=" << weight << endl;
	}

};

二、编程题:
1、答案:
#include
#include
using namespace std;

int main() {
int a, b;
cin >> a >> b;
if (a % b == 0)
cout << a + b << endl;
else
cout << a - b << endl;
return 0;
}
7-2 逆序整数
分数 10
全屏浏览题目
切换布局
作者 葛亮
单位 重庆大学
对于n位的两个正整数x和y,可以把x表示为x1x2…xn,其中xi(1≤i≤n)表示整数x第i位上的数字;把y表示为y1y2…yn,其中yi(1≤i≤n)表示整数y第i位上的数字。如果x1+k=yn−k(0≤k≤n−1)始终成立,则x和y互为逆序整数。
给你两个正整数A和B, 判断两个整数是否互为逆序整数,并输出相应的结果。
注:题目保证正整数A和B的个位数字不是0。
输入格式:
先在第一行输入位数n,然后在接下来的两行分别输入位数为n的正整数A和B(1≤n≤50)。
输出格式:

2、答案:
#include
#include <math.h>
#include
using namespace std;

int main() {
int n;
string x, y;
int k;
int l = 1;
string sx, sy;
cin >> n;
cin >> x >> y;

for (k = 0; k <= n - 1; k++) {
	sx = x.substr(k, 1);
	sy = y.substr(n - k - 1, 1);
	if ( sx == sy )
		l *= 1;
	else
		l *= 0;
}

if (l != 0)
	cout << x << " and " << y << " are reverse." << endl;
else
	cout << x << " and " << y << " are not reverse." << endl;
return 0;

}
方法二
#include
#include
#include
using namespace std;
int main()
{
string s = “”;
int n;
string c,a;
cin>>n;
cin>>s;
cin>>a;
c=s;
reverse(s.begin(), s.end());
if(a==s){
cout<<c<<" and “<<a<<” are reverse.“;
}
else{
cout<<c<<” and “<<a<<” are not reverse.";}
return 0;
}
-3 一维世界的疫情传播
分数 10
全屏浏览题目
切换布局
作者 葛亮
单位 重庆大学
可怕的阿尔法病毒正在一维世界传播,如果某人的活动范围与病毒携带者的活动范围有交集,则有被感染的可能。假设有一名病毒携带者A在位于X的家附近活动,他到过的地方用xi表示(这些地点不重复),对于X和xi之间的区域,都认为是A的活动范围。另外有一名健康者B,他在位于Y的家附近活动,他到过的地方用yi表示(这些地点不重复),对于Y和yi之间的区域,都认为是B的活动范围。所有的地点都位于整数点上,−100≤X,Y,xi,yi≤100,X=Y,xi=X,yi=Y。现在需要判断B是否有被感染的可能。

3、答案:

#include
#include
#include
using namespace std;

int main() {
int N, M, X, Y;
vector x;
vector y;
int i, j, k;
int l = 0;
cin >> N >> M >> X >> Y;

for (i = 0; i <= N - 1; i++) {
	cin >> k;
	x.push_back(k);
}
for (i = 0; i <= M - 1; i++) {
	cin >> k;
	y.push_back(k);
}

sort(x.begin(), x.end());
sort(y.begin(), y.end());
for (i = 0; i < M; i++)
	if ((x[0] < X) && (X < x[N - 1]))
		if ((x[0] < Y ) && (Y < x[N - 1])
		        && (x[0] < y[i] ) && (y[i] < x[N - 1]))
			l++;
		else if (Y > x[N - 1] && y[i] < x[N - 1])
			l++;
		else if (Y < x[0] && y[i] > x[0])
			l++;
		else
			continue;
	else if (X < x[0])

		if (X < Y < x[N - 1])
			l++;
		else if ((Y < X) && (y[i] > X))
			l++;
		else if ((Y > x[N - 1]) && y[i] < x[N - 1])
			l++;
		else
			continue;
	else if (X > x[N - 1])
		if (x[0] < Y < X)
			l++;
		else if ((Y < x[0]) && (y[i] > x[0]))
			l++;
		else if ((Y > X) && y[i] < X)
			l++;
		else
			continue;
	else
		continue;
if (l > 0)
	cout << X << " and " << Y << ": possible";
else
	cout << X << " and " << Y << ": impossible";

return 0;

}

类,继承与多态
6-1 设计实现大整数类
class HugeInteger
{
private:
int n[101];
public:
HugeInteger();
HugeInteger(int n1);
HugeInteger(string n1);
void printa();

friend ostream& operator<<(ostream& os, const HugeInteger& n1);

HugeInteger operator+ (const HugeInteger& n2)
{
	HugeInteger temp;
	int temp1 = 0;
	int temp2 = 0;
	int judge = 0;
	for (int i = 100; i >= 0; i--)
	{
		temp1 = this->n[i] + n2.n[i] +temp2;
		judge = temp1 / 10;
		if (judge == 0)
		{
			temp2 = 0;
		}
		else
		{
			temp2 = 1;
		}
		temp.n[i] = temp1 % 10;
	}
	return temp;
}

HugeInteger operator+ (const int& n2)
{
	HugeInteger temp;
	int temp1 = 0;
	int temp2 = 0;
	int temp3 = 1;
	int judge = 0;
	for (int i = 100; i >= 0; i--)
	{
		if ((n2 / temp3 % 10) != 0)
		{
			temp1 = this->n[i] + (n2 / temp3 % 10) +temp2;
			temp3 *= 10;
			judge = temp1 / 10;
			if (judge == 0)
			{
				temp2 = 0;
			}
			else
			{
				temp2 = 1;
			}
			temp.n[i] = temp1 % 10;
		}
		else
		{
			if (temp2 == 1)
			{
				temp.n[i] = this->n[i] + 1;
				temp2 = 0;
			}
			else
			{
				temp.n[i] = this->n[i];
			}
		}
	}
	return temp;

}

HugeInteger operator+ (const string& n3)
{
	HugeInteger temp;
	int temp1 = 0;
	int temp2 = 0;
	int judge = 0;
	int n2[101] = { 0 };
	
	int len = n3.length() - 1, len1 = n3.length() - 1;
	for (int i = 100; i >= 100 - len1; i--)
	{
		n2[i] = int(n3[len]) - 48;
		len = len - 1;
	}

	for (int i = 100; i >= 0; i--)
	{
		temp1 = this->n[i] + n2[i] + temp2;
		judge = temp1 / 10;
		if (judge == 0)
		{
			temp2 = 0;
		}
		else
		{
			temp2 = 1;
		}
		temp.n[i] = temp1 % 10;
	}
	return temp;
}

};

HugeInteger::HugeInteger()
{
for (int i = 0; i <=100; i++)
{
this->n[i] = 0;
}
}
HugeInteger::HugeInteger(int n1)
{
for (int i = 0; i <= 100; i++)
{
this->n[i] = 0;
}
int temp = 1;
for (int i = 100;(n1/temp)!=0; i–)
{
this->n[i] = n1/temp % 10;
temp *= 10;
}
}

ostream& operator<<(ostream& os,const HugeInteger& n1)
{
int judge = 0;
for (int i = 0; i <= 100; i++)
{

	if (n1.n[i] == 0 && judge == 0)
	{
		continue;
	}
	else
		judge = 1;
	if (judge == 1)
	{
		os << n1.n[i];
	}
}
if (judge == 0)
{
	os << 0;
}
return os;

}

HugeInteger::HugeInteger(string n1)
{
for (int i = 0; i <= 100; i++)
{
this->n[i] = 0;
}
int temp = 1;
int len=n1.length() - 1 , len1 = n1.length() - 1 ;
for (int i = 100; i >= 100 - len1; i–)
{
this->n[i] = int(n1[len]) - 48;
len = len - 1;
}

}

void HugeInteger::printa()
{
int judge = 0;
for (int i = 0; i <= 100; i++)
{

	if(this->n[i] == 0 && judge == 0)
	{
		continue;
	}
	else
		judge = 1;
	if (judge == 1)
	{
		cout << n[i];
	}
}
if (judge == 0)
{
	cout << 0;
}
cout << endl;

}

-1 挑选苹果
果园采摘了n个苹果,分别放在若干个篮筐中。现给出n个苹果所在篮筐的情况,请找出每个篮筐中重量最重的苹果。定义一个苹果类Apple,有编号(id)、重量(weight)、直径(diameter)成员变量。
输入格式:
首先输入一个整型数n(1<=n<=999999),表示n个苹果。
紧跟着n行输入,每一行格式为:篮筐号,苹果编号(id),重量(weight),直径(diameter)。
篮筐号为整数,取值区间为[1,999999],id为字符串,weight、diameter为正整数。
输出格式:
按篮筐号从小到大排序,输出每个篮筐中重量最重的苹果信息。题目保证每个篮筐中只有一个重量最重的苹果。
输入样例:
7
1 N000001 175 77
2 N000002 180 83
2 N000003 160 66
1 N000004 160 63
1 N000005 165 68
4 N000006 183 85
2 N000007 170 74

#include
#include
using namespace std;
class apple
{
public:
int num;
string id;
int weight;
int diameter;
};
int main()
{
int n;
cin>>n;
apple app[n];
for(int i=0;i<n;i++)
{
cin>>app[i].num>>app[i].id>>app[i].weight>>app[i].diameter;
}
int basket[999999+1]={0};
for(int i=0;i<n;i++)
{
basket[app[i].num]++;
}//统计篮子数量,若basket不等于0,那么就说明有
int max[999999+1]={0};//表示其最大的编号,若不存在则编号为0,其非0元素个数应该与baket数组一样;
for(int i=0;i<999999;i++)
{
if(basket[i+1]!=0)//存在的篮子,编号为i+1
{

        for(int j=0;j<n;j++)
        {
            if(max[i+1]<=app[j].weight&&i+1==app[j].num)
            {
                max[i+1]=app[j].weight;
            }
        }
        
    }
}
for(int i=0;i<999999;i++)
{
    if(basket[i+1]!=0)
    {
        for(int j=0;j<n;j++)
        {
            if(max[i+1]==app[j].weight&&i+1==app[j].num)
                cout<<i+1<<" "<<app[j].id<<" "<<app[j].weight<<" "<<app[j].diameter<<endl;
        }
    }
}
return 0;

}

7-2 国际贸易统计
这里给出N个国家之间进行国际贸易的记录,请你统计这些国家进行国际贸易的收益。
输入格式:
输入第一行给出一个正整数N(≤104),即参与国际贸易的国家数量,则这些国家从1到N编号。随后N行,第i行给出编号为i的国家在贸易中卖出商品的记录,格式如下:kN1P1⋯NkPk,
其中k(0≤k≤20)是买入商品国家的个数,Ni是买入商品国家的编号,Pi>0是其买入商品的金额(整数表示,以万元为单位)。注意:一次贸易对于买入和卖出国家的贸易次数都会增加1次。
输出格式:
按照收入金额从高到低的递减顺序输出每个国家的编号和收入金额(整数表示,以万元为单位)。每个国家的信息占一行,两数字间有1个空格。如果收入金额有并列,则按参与国际贸易的次数递减输出;如果还有并列,则按国家编号递增输出。
输入样例:
#include
using namespace std;
class country
{
public:
int _num;
int _count = 0;
int _sum = 0;
int _sum2 = 0;
int _profit = 0;
public:
country() {};
country(country& a);
void set(int num, int count, int sum, int sum2);
void show();
};
country::country(country& a)
{
_num = a._num;
_count = a._count;
_sum = a._sum;
_sum2 = a._sum2;
_profit = a._profit;
}
void country::set(int num, int count, int sum, int sum2)
{
_num = num;
_count = count;
_sum = sum;
_sum2 = sum2;
_profit = sum - sum2;
}
void country::show()
{
cout << this->_num << " " << this->_profit << endl;
}
int main()
{
int n;
cin >> n;
country a[n];
int k[n];
for (int i = 0; i < n; i++)
{
int sum = 0;
int N[n], money[n];
for (int t = 0; t < n; t++)
{
N[t] = 0;
money[t] = 0;
}
cin >> k[i];
for (int j = 0; j < k[i]; j++)
{
cin >> N[j] >> money[j];
a[N[j] - 1]._count++, a[N[j] - 1]._sum2 += money[j];
a[i]._count++;
a[i]._sum += money[j];
}
}
for (int i = 0; i < n; i++)
{
a[i].set(i + 1, a[i]._count, a[i]._sum, a[i]._sum2);
}
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
country temp = a[j + 1];
if (a[j]._profit < a[j + 1]._profit)
{
a[j + 1] = a[j];
a[j] = temp;
}
}
}
for (int i = 0; i < n - 1; i++)
{
if (a[i]._profit == a[i + 1]._profit)
{
if (a[i]._count < a[i + 1]._count)
{
int temp2 = a[i + 1]._num;
a[i + 1]._num = a[i]._num;
a[i]._num = temp2;
}
}
}
for (int i = 0; i < n; i++)
{
if (i != n - 1)
a[i].show();
else
cout << a[i]._num << " " << a[i]._profit;
}
}

6-1 水上飞机*
分数 10
全屏浏览题目
切换布局
作者 李祥
单位 湖北经济学院
请设计以下航行器、飞机、船、水上飞机等 4 个类。
• CRAFT 为航行器类,是公共基类,提供航行器的基本特性。包括:
一个保护数据成员:speed(速度)。
三个公有成员函数:构造函数(初始化速度)、析构函数和 Show 函数(显示速度)。
• PLANE 为飞机类,以公有方式继承 CRAFT 类,在航行器类的基础上增加飞机的特性。包括:
一个保护数据成员:width(翼展)。
三个公有成员函数:构造函数(初始化速度和翼展)、析构函数和 Show 函数(显示速度和翼展)。
• SHIP 为船类,以公有方式继承 CRAFT 类,在航行器类的基础上增加船的特性。包括:
一个保护数据成员:depth(吃水深度)。
三个公有成员函数:构造函数(初始化速度和吃水深度)、析构函数和 Show 函数(显示速度和吃水深度)。
• SEAPLANE 为水上飞机类,同时以公有方式继承 PLANE 类和 SHIP 类,兼具飞机和船的特性。包括:
三个公有成员函数:构造函数(初始化速度、翼展、吃水深度)、析构函数和 Show 函数(显示速度、翼展和吃水深度)。
测试用例
class CRAFT {
protected:
double speed;
public:
CRAFT(double s) {
speed = s;
cout << "创建航行器(速度: " << speed << ‘)’ << endl;

	}
	virtual void Show() {
		cout << "航行(速度: " << speed << ')' << endl;
	}
	virtual ~CRAFT() {
		cout << "销毁航行器(速度: " << speed << ')' << endl;
	}

};

class PLANE: virtual public CRAFT {
protected:
double width;
public:
PLANE(double s, double w): CRAFT(s), width(w) {
cout << "创建飞机(翼展: " << width << ‘)’ << endl;
}
virtual ~PLANE() {
cout << "销毁飞机(翼展: " << width << ‘)’ << endl;
}
virtual void Show() {
cout << "航行(速度: " << speed << ", 翼展: " << width << ‘)’ << endl;
}
};

class SHIP: virtual public CRAFT {
protected:
double depth;
public:
SHIP(double s, double d): CRAFT(s), depth(d) {
cout << "创建船(吃水: " << depth << ‘)’ << endl;
}
virtual void Show() {
cout << "航行(速度: " << speed << ", 吃水: " << depth << ‘)’ << endl;
}
virtual ~SHIP() {
cout << "销毁船(吃水: " << depth << ‘)’ << endl;
}
};

class SEAPLANE: public PLANE, public SHIP {/这里继承的顺序要先PLANE再SHIP,才能得到输出样例的结果/
public:
SEAPLANE(double s, double w, double d): CRAFT(s), PLANE(s, w), SHIP(s, d) {
cout << “创建水上飞机” << endl;
}
virtual ~SEAPLANE() {
cout << “销毁水上飞机” << endl;
}
virtual void Show() {
cout << "航行(速度: " << speed << ", 翼展: " << width << ", 吃水: " << depth << ‘)’ << endl;
}
};
6-2 私有继承派生类使用基类的成员函数
按要求完成下面的程序:

1、定义一个Animal类,成员包括:

(1)整数类型的私有数据成员m_nWeightBase,表示Animal的体重;

(2)整数类型的保护数据成员m_nAgeBase,表示Animal的年龄;

(3)公有函数成员set_weight,用指定形参初始化数据成员m_nWeightBase;

(4)公有成员函数get_weight,返回数据成员m_nWeightBase的值;

(5)公有函数成员set_age,用指定形参初始化数据成员m_nAgeBase;

2、定义一个Cat类,私有继承自Animal类,其成员包括:

(1)string类型的私有数据成员m_strName;

(2)带参数的构造函数,用指定形参对私有数据成员进行初始化

(3)公有的成员函数set_print_age,功能是首先调用基类的成员函数set_age设置数据成员m_nAgeBase的值为5,接着输出成员m_strName的值,然后输出“, age = ”,最后输出基类的数据成员m_nAgeBase的值。具体输出格式参见main函数和样例输出。

(4)公有的成员函数set_print_weight,功能是首先调用基类的成员函数set_weight设置数据成员nWeightBase的值为6,接着输出成员m_strName的值,然后输出“, weight = ”,最后调用基类的成员函数get_weight输出基类的数据成员m_nAgeBase的值。具体输出格式参见main函数和样例输出。
类和函数接口定义:
class Animal{
private:
int m_nWeightBase;
protected:
int m_nAgeBase;
protected:
void set_weight(int i){
m_nWeightBase=i;
}
int get_weight(){
return m_nWeightBase;
}
void set_age(int i){
m_nAgeBase=i;
}
};
class Cat:private Animal{
private:
string m_strName;
public:
Cat(string s){

    m_strName=s;
}
void set_print_age(){
    set_age(5);
    cout<<m_strName<<", age = "<<m_nAgeBase<<endl;
}
void set_print_weight(){
    set_weight(6);
    cout<<m_strName<<", weight = "<<get_weight()<<endl;
}

};

6-3 猪上树
#include
using namespace std;
/* 请在这里填写答案 */

int main()
{
Pig *p1 = new Pig;
Pig *p2 = new MagicPig;
cout << endl;

p1->climb(); 
p2->climb(); 
cout << endl; 

delete p1; 
delete p2;  
return 0;

}
输入样例:
class Pig
{
public:
Pig()
{
cout<<“Pig 申请了空间…”<<endl;
}
virtual ~Pig()
{
cout<<“Pig 释放了空间…”<<endl;
}
virtual void climb()
{
cout<<“我只是个平凡的猪猪。”<<endl;
}
};
class MagicPig:public Pig
{
public:
MagicPig()
{
cout<<“MagicPig 申请了空间…”<<endl;
}
~MagicPig()
{
cout<<“MagicPig 释放了空间…”<<endl;
}
void climb()
{
cout<<“我能上树了耶!”<<endl;
}
};

Vctor
#include
using namespace std;

/* 请在这里填写答案 */

int main()
{
Vector vint;
int n,m;
cin >> n >> m;
for ( int i=0; i<n; i++ ) {
// add() can inflate the vector automatically
vint.add(i);
}
// get_size() returns the number of elements stored in the vector
cout << vint.get_size() << endl;
cout << vint[m] << endl;
// remove() removes the element at the index which begins from zero
vint.remove(m);
cout << vint.add(-1) << endl;
cout << vint[m] << endl;
Vector vv = vint;
cout << vv[vv.get_size()-1] << endl;
vv.add(m);
cout << vint.get_size() << endl;
}
输入样例:
template
class Vector
{
private:
int pos;
int size = 100;
T* data;
public:
Vector() {
pos = 0;
data = new T[size];
}
int add(T m) {
data[pos]=m;
pos++;
return pos-1;
}
int get_size() { return pos; }
void remove(int m) {
for (int i = m; i < pos-1; i++) {
data[i] = data[i + 1];
}
pos–;
}
const T& operator[](int index)const
{
return data[index];
}
};

指针与函数
7-1 无符号整数的内部结构 - C/C++ 指针及引用
分数 10
全屏浏览题目
切换布局
作者 海洋饼干叔叔
单位 重庆大学
无符号整数v由4个字节构成。请编程完成下述任务:

  1. 从键盘读取一个整数,存入unsinged int v;
  2. 以16进制格式打印v的值;
  3. 取v的地址,并强制类型转换成unsigned char*,然后通过这个地址/指针依次打印构成v的第0,第1,第2,第3个字节的16进制值。
    #include
    using namespace std;
    int main()
    {
    int v;
    cin>>v;
    cout<<hex;
    cout<<v<<endl;
    unsigned charp=(unsigned char)&v;
    for(int i=0;i<4;i++)
    {
    cout<<int(p[i]);
    if(i!=3)
    {
    cout<<" ";
    }
    }
    return 0;
    }

产生学生成绩随机为0-100
#include<stdio.h>
#include<malloc.h>
int main(){
int N;
double p,sum=0,max=0,min=100;
scanf(“%d”,&N);
if((p=(double
)malloc(N*(sizeof(double))))==NULL){
return 0;
}
for(int i=0;i<N;i++){
scanf(“%lf”,p+i);
max=((p+i)>max)?(p+i):max;
min=((p+i)<min)?(p+i):min;
sum+=*(p+i);
}
printf(“average = %.2lf\nmax = %.2lf\nmin = %.2lf\n”,sum/N,max,min);
return 0;
}
3 滤字符
以指针的方式,将某个字符串中出现的特定字符删去,然后输出新的字符串。首先输入一个正整数T,表示测试数据的组数,然后是T组测试数据。
每组测试数据输入一个字符串s和一个非空格字符t。其中s的长度不超过100,且只包含英文字母。
对于每组测试,将删掉t后新得到的字串输出。如果串被删空,则输出“NULL”(引号不必输出)。
#include
#include <stdio.h>
#include
#include
using namespace std;

int main()
{
//t组测试数据
int t = 0;
cin >> t;

for (int i = 0; i < t; i++)
{
    //输入字符串
    char ch[100] = { 0 };
    cin >> ch;

    //输入需替换字符
    char zi = 'a';
    cin >> zi;

    //建立指针
    char* p = &ch[0];

    //思想:若是需要替换的字符,用下一个覆盖,之后的字符以此类推
    for (; *p != 0; )
    {
        //若有多个需要替换,每次循环只替换了一个
        if (*p == zi)
        {
            for (char* i = p; *i != 0; i++)
            {
                *i = *(i + 1);
            }
        }

        else if (*p != zi)
        {
            p++;
        }
    }

    //输出
    if (ch[0] == 0)
    {
        cout << "NULL" << endl;
    }
    else
    {
        cout << ch << endl;
    }
}

return 0;

}
7-4 平均之上
输入一个整数n,再输入n个成绩,求大于平均分的成绩个数。
例如,输入5 68 79 56 95 88,输出3。
#include <stdio.h>
#define MAXN 100000

int main()
{
int n, T, i;
scanf(“%d”, &T);
// T决定了这个循环运行的次数
for (int q = 0; q < T; q++)
{
scanf(“%d”, &n); //输入个数n
int a[MAXN];

    //存放数据
    for (i = 0; i < n; i++)
        scanf(" %d", &a[i]);

    //求和并计算平均值
    int sum = 0, aver, count = 0;
    for (i = 0; i < n; i++)
        sum += a[i];
    aver = sum / n;

    //将a[i]与平均值作对比
    for (i = 0; i < n; i++)
        if (a[i] > aver)
            count++; // a[i]大于平均值,计数加一
    //运行完上述步骤,输出这个数组中超过平均值的人数
    printf("%d\n", count);
}
return 0;}

7-5 9-13竞赛排名
有m个选手n个评委,每个评委给所有选手打分。最后得分的计算规则为去掉一个最高分,去掉一个最低分后取平均分为最后得分。要求按得分从高到低排出名次,公布获奖名单。本题要求用行指针实现。1≤m,n≤10。请务必用冒泡排序。
#include<stdio.h>
float swap(float *x,float *y)
{
float temp;
temp=*x;
*x=*y;
*y=temp;
}
float average(float score[],int n)
{
float sum=0;
for(int i=0;i<n-1;i++)
{
for(int j=0;j<n-i-1;j++)
{
if(score[j]<score[j+1])
{
swap(&score[j],&score[j+1]);
}
}
}
for(int i=1;i<n-1;i++)
{
sum+=score[i];
}
return sum/(n-2);
}
int main()
{
int m,n;
int temp;
scanf(“%d %d”,&m,&n);
float score[m][n];
float r[m];
int c[10]={1,2,3,4,5,6,7,8,9,10};
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
scanf(“%f”,&score[i][j]);
}
}
for(int i=0;i<m;i++)
{
r[i]=average(score[i],n);
}
for(int i=0;i<m-1;i++)
{
for(int j=0;j<m-i-1;j++)
{
if(r[j]<r[j+1])
{
swap(&r[j],&r[j+1]);
temp=c[j];
c[j]=c[j+1];
c[j+1]=temp;
}
}
}
for(int i=0;i<m;i++)
{
printf(“%3d”,c[i]);
}
return 0;}

6-1函数重载实现两数相加
int add(int x,int y)
{
int add = x + y;
return add;
}
double add(double x,double y)
{
double add = x + y;
return add;
}
string add(string x,string y)
{
string add = x + y;
return add;
}

7-1 敲笨钟
微博上有个自称“大笨钟V”的家伙,每天敲钟催促码农们爱惜身体早点睡觉。为了增加敲钟的趣味性,还会糟改几句古诗词。其糟改的方法为:去网上搜寻压“ong”韵的古诗词,把句尾的三个字换成“敲笨钟”。例如唐代诗人李贺有名句曰:“寻章摘句老雕虫,晓月当帘挂玉弓”,其中“虫”(chong)和“弓”(gong)都压了“ong”韵。于是这句诗就被糟改为“寻章摘句老雕虫,晓月当帘敲笨钟”。
现在给你一大堆古诗词句,要求你写个程序自动将压“ong”韵的句子糟改成“敲笨钟”。
输入格式:
输入首先在第一行给出一个不超过 20 的正整数 N。随后 N 行,每行用汉语拼音给出一句古诗词,分上下两半句,用逗号 , 分隔,句号 . 结尾。相邻两字的拼音之间用一个空格分隔。题目保证每个字的拼音不超过 6 个字符,每行字符的总长度不超过 100,并且下半句诗至少有 3 个字。
输出:对每一行诗句,判断其是否压“ong”韵。即上下两句末尾的字都是“ong”结尾。如果是压此韵的,就按题面方法糟改之后输出,输出格式同输入;否则输出 Skipped,即跳过此句。
#include
#include
using namespace std;

int main()
{
int N;
cin >> N;
cin.ignore();
string cs;
for (int i = 0, n; i < N; i++)
{
getline(cin, cs);
n = cs.length()-1;
if (cs.find(“ong,”) != string::npos && cs.rfind(“ong.”) != cs.npos)
{
for (int i = 0; i < 3; i++)
{
n = cs.rfind(" ", n) - 1;
}
cs.erase(n + 2);
cs += “qiao ben zhong.”;
cout << cs << endl;
}
else
{
cout << “Skipped” << endl;;
}
}
}

7-3幸福数
无则输出SAD
#include
#include
#include

class Set_H//集合
{
public:
void Add(const int& x)
{
Copy();
P[count - 1] = x;
}
void Add(int& x, bool)
{
for (int i = 0; i < count; i++)
{
if (x == P[i])
return;
}
Add(x);
}
void Copy()
{
int* cache = new int[++count];
for (int i = 0; i < count -1; i++)
cache[i] = P[i];
delete[] P;
P = cache;
}
int& operator[](const int& p)
{
return P[p];
}
~Set_H()
{
delete[] P;
}
public:
int* P = new int[1];
int count = 0;
};

int pow_2[10]{};//保存平方
int iter[30];//暂存迭代过程的数
Set_H HA, Single;//保存幸福数和其独立性
Set_H prime, attachment;//质数表和依附表
bool isHappy(const int& x, int count = 1)
{
if (count > 30)//最多迭代30次
return false;
int bits = std::to_string(x).length();
int sum = 0;
if (bits != 1)
{
int base = 1;
for (int i = 1; i < bits; i++)
base *= 10;
for (sum = pow_2[x / base] + pow_2[x % 10]; bits > 2; bits–, base /= 10)
sum += pow_2[x % base / (base / 10)];
}
else
sum = x * x;
if (sum == 1)
{
Single.Add(count);
return true;
}
else//没有成功,进入迭代
{
iter[count - 1] = sum;
return isHappy(sum, count + 1);
}
}

bool is_preme(const int& x)//判断质数
{
for (int i = sqrt(x); i > 1; i–)
{
if (x % i == 0)
return false;
}
return true;
}

int main()
{
for (int i = 0; i < 10; i++)//计算各数平方
pow_2[i] = i * i;
int A, B;
std::cin >> A >> B;
for (int i = 2; i < B + 1; i++)
{
if (is_preme(i))
prime.Add(i);
}
for (int i = A; i < B + 1; i++)
{
for (int c = 0; c < attachment.count; c++)//判断是否独立
{
if (i == attachment[c])
goto reloop;//下一次循环
}
for (int i = 0; iter[i] != 0 && i < 30; i++)
iter[i] = 0;//初始化为0
if (isHappy(i))
{
HA.Add(i);
for (int i = 0; iter[i] != 0 && i < 30; i++)
{
if (A <= iter[i] && iter[i] <= B)
attachment.Add(iter[i], true);//加入依附表
}
}
reloop:;
}
for (int i = 0; i < HA.count; i++)
{
for (int c = 0; c < attachment.count; c++)//判断是否独立
{
if (attachment[c] == HA[i])
goto next;//下一次循环
}
for (int c = 0; c < prime.count; c++)//遍历质数表
{
if (HA[i] == prime[c])
{
Single[i] *= 2;
break;
}
}
std::cout << HA[i] << " " << Single[i] << “\n”;
next:;
}
if (HA.count == 0)
std::cout << “SAD”;
return 0;
}

运用函数编写程序
7-1 简单求阶乘问题
输入:4
输出样例:24
#include
using namespace std;
long long fac(int& X)
{
long long sum = X;
while(X > 1)
{ X–;
sum *= X;
}
return sum;
}
int main()
{
int N;
cin>>N;
cout<<fac(N);
}
均方差
#include<stdio.h>
#include
#include
#include
using namespace std;
int main(){
int N;
double sum = 0;
cin >> N;
int A[N];
for(int i = 0; i < N; ++i)
{
cin >> A[i];
sum += A[i];
}
double Avg = sum/N;
double N2 = 0;
for(int i = 0; i < N; ++i){
N2 += pow((A[i] - Avg),2);
}
N2 /= N;
N2 = sqrt(N2);
cout <<fixed<<setprecision(5)<< N2 << endl;
}

数组与结构体
杨辉三角
#include<stdio.h>

int main()
{
int arr[11][11];
int n=0;
arr[0][0]=0;

//输出n
scanf("%d",&n);

//打印,先控制行数外层循环
for(int i=0;i<n;i++)
{
    //打印空格
    for(int k=0;k<n-i-1;k++)
    {
        printf(" ");
    }
    
    //打印数据
    for(int j=0;j<=i;j++)
    {
        //这个画图找规律,放在二维数组里,第一行就是0行,然后每行的最后一个1,i与j相同换行,第一个元素也是1,j=0然后根据杨辉三角的规律写中间元素
        if(i==j)
        {
            arr[i][j]=1;
        }
        else if(j==0)
        {
            arr[i][j]=1;
        }
        else
        {
            arr[i][j]=arr[i-1][j-1]+arr[i-1][j];
        }
        printf("%4d",arr[i][j]);
        if(i==j)
        {
            printf("\n");
        }
    }
}
return 0;

}

刮彩票
数字合计 获得金币 数字合计 获得金币
6 10,000 16 72
7 36 17 180
8 720 18 119
9 360 19 36
10 80 20 306
11 252 21 1,080
12 108 22 144
13 72 23 1,800
14 54 24 3,600
15 180
#include <stdio.h>
int main(){
int a[3][3],sign=0,i,j,flag[10]={0},b[3][2],n,sum=0,c[19]={10000,36,720,360,80,252,108,72,54,180,72,180,119,36,306,1080,144,1800,3600};
for(i=0;i<3;i++){
for(j=0;j<3;j++){
scanf(“%d”,&a[i][j]);
flag[a[i][j]]++;
}
}
for(i=0;i<10;i++){
if(flag[i]0)
sign=i;
}
for(i=0;i<3;i++){
for(j=0;j<3;j++){
if(a[i][j]0)
a[i][j]=sign;
}
}
for(i=0;i<3;i++){
for(j=0;j<2;j++){
scanf(“%d”,&b[i][j]);
}
}
scanf(“%d”,&n);
if(n<=3){
for(i=0;i<3;i++){
sum+=a[n-1][i];
}
}
if(n>3&&n<=6){
for(i=0;i<3;i++){
sum+=a[i][n-4];
}
}
if(n
7)
sum=a[0][0]+a[1][1]+a[2][2];
if(n
8)
sum=a[0][2]+a[1][1]+a[2][0];
printf(“%d\n”,a[b[0][0]-1][b[0][1]-1]);
printf(“%d\n”,a[b[1][0]-1][b[1][1]-1]);
printf(“%d\n”,a[b[2][0]-1][b[2][1]-1]);
for(i=0;i<19;i++){
if((sum-6)==i){
printf(“%d”,c[i]);
break;
}
}
}

7-5 有理数比较输入格式:
输入在一行中按照“a1/b1 a2/b2”的格式给出两个分数形式的有理数,其中分子和分母全是整形范围内的正整数。
输出格式:
在一行中按照“a1/b1 关系符 a2/b2”的格式输出两个有理数的关系。其中“>”表示“大于”,“<”表示“小于”,“=”表示“等于”。
输入样例1:
1/2 3/4
#include<stdio.h>
struct rational
{
int a;
char c;
int b;
}m1,m2;
int max(int a,int b)
{
int i,m=b,n=a;
while(m!=0)
{
i=n%m;
n=m;
m=i;
}
i=ab/n;
return i;
}
int main()
{
struct rational m1,m2;
int i,j;
scanf(“%d%c%d %d%c%d”,&m1.a,&m1.c,&m1.b,&m2.a,&m2.c,&m2.b);
i=(max(m1.b,m2.b))/m1.b;
j=(max(m1.b,m2.b))/m2.b;
if(m1.a
i>m2.aj)
{
printf(“%d%c%d > %d%c%d”,m1.a,m1.c,m1.b,m2.a,m2.c,m2.b);
}
else if(m1.a
i==m2.aj)
{
printf(“%d%c%d = %d%c%d”,m1.a,m1.c,m1.b,m2.a,m2.c,m2.b);
}
else if(m1.a
i<m2.a*j)
{
printf(“%d%c%d < %d%c%d”,m1.a,m1.c,m1.b,m2.a,m2.c,m2.b);
}
return 0;
}

STL容器的编程实现
部分排序
#include
#include
#include <string.h>
#include
#include
#include <math.h>
#include
#include
using namespace std;

int main(){

ios::sync_with_stdio(false);

int n,r;
cin>>n>>r;

int a[n];

for(int i=0;i<n;i++){
	cin>>a[i];
}

if(r+r>=n){
	for(int i=0;i<n;i++){
		if(i!=0)
		cout<<" ";
		cout<<a[i];
	}
}
else{
	sort(a+r,a+n-r);
	for(int i=0;i<n;i++){
		if(i!=0)
		cout<<" ";
		cout<<a[i];
	}
}

return 0;

}

7-3 找出不是两个数组共有的元素
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int i, j, m, n, a[25], b[25], c[25], k = 0, flag, equal;
scanf(“%d”, &m);
for(i = 0; i < m; i++)
scanf(“%d”, &a[i]);
scanf(“%d”, &n);
for(i = 0; i < n; i++)
scanf(“%d”, &b[i]);
for(i = 0; i < m; i++)
{
flag = 0;
for(j = 0; j < i; j++)
if(a[i] == a[j])
flag = 1;
if(!flag)
{
equal = 0;
for(j = 0; j < n; j++)
if(a[i] == b[j])
{
equal = 1;
break;
}
if(!equal)
c[k++] = a[i];
}
}
for(i = 0; i < n; i++)
{
flag = 0;
for(j = 0; j < i; j++)
if(b[i] == b[j])
flag = 1;
if(!flag)
{
equal = 0;
for(j = 0; j < m; j++)
if(b[i] == a[j])
{
equal = 1;
break;
}
if(!equal)
c[k++] = b[i];
}
}
printf(“%d”, c[0]);
for(i = 1; i < k; i++)
printf(" %d", c[i]);
printf(“\n”);
return 0;
}

控制语句
分别输出这n个整数的和、平均值、乘积、最小值和最大值。每个结果各占一行。其中,平均值保留1位小数(四舍五入)。输入样例:132714-1输出样例:Sum is 54 Average is 18.0 Product is 4914 Smallest is 13 Largest is 27
#include<stdio.h>
#include
#include
#include
#include
using namespace std;
int main(){
int n1;
float ave;
vector a;
while (cin >> n1){
if (n1 == -1) break;
a.push_back(n1);
}
int sum = 0;
int mult = 1;
for (unsigned int i = 0; i < a.size(); ++i){
mult *= a[i];
sum += a[i];
}
sort(a.begin(), a.end());
int min = *a.begin();
int max = a[a.size()-1];
ave = (float)sum / a.size();
printf(“Sum is %d\n”,sum);
printf(“Average is %.1f\n”,ave);
printf(“Product is %d\n”,mult);
printf(“Smallest is %d\n”,min);
printf(“Largest is %d”,max);
return 0;
}
7-3 打印指定大小的棋盘格
分数 10




#include
using namespace std;

int main()
{
int n;
cin>>n;
for (int i=0;i<n;i++)
{
if(i%2!=0)
for (int j=0;j<n;j++)
cout<<" “;
if(i%2==0)
for (int j=0;j<n;j++)
cout<<”
“;
cout<<”\n";
}
return 0;
}
本题目要求读入1个整数N(0≤N<108),然后打印输出该整数各位数字,相邻位数字之间间隔3个空格。123456输出样例:在这里给出相应的输出。例如:
1 2 3 4 5 6注意:输出的各个数字之间间隔三个空格。
#include
using namespace std;

int main()
{
int N;
int a=1,b;
cin>>N;
b = N;

while(b>10)
{
    a*=10;
    b/=10; 
}

while(a!=1)
{
    cout<<N/a<<"   ";
    N%=a;
    a/=10;
}
cout<<N/a;

return 0;

}
输出相应精度的e值,保留n+1位小数(四舍五入)。输入样例:3
#include
#include
using namespace std;
int main()
{
int n;
double e=1.0,m=1.0;
cin>>n;
for(int i=1;i<=n+3;i++)
{
m = mi;
e+=(1/m);
}
cout<<fixed<<setprecision(n+1)<<e;
return 0;
}
后天
#include
using namespace std;
int main()
{
int D=3;
cin>>D;
if(D+2<=7)
cout<<D+2;
else
cout<<D+2-7;
}
三个整数的统计
#include
#include
using namespace std;
int main(){
int sum,pro,minV=2147483647,maxV=-2147483648;
int n1,n2,n3;
float ave;
cin>>n1>>n2>>n3;
sum = n1+n2+n3;
ave = 1.0
sum/3;
pro = n1n2n3;
minV = minV<n1?minV:n1;
minV = minV<n2?minV:n2;
minV = minV<n3?minV:n3;
maxV = maxV>n1?maxV:n1;
maxV = maxV>n2?maxV:n2;
maxV = maxV>n3?maxV:n3;
cout<<"Sum is "<<sum<<endl<<"Average is "<<fixed<<setprecision(1)<<ave<<endl<<"Product is "<<pro<<endl<<"Smallest is "<<minV<<endl<<"Largest is "<<maxV;
return 0;
}

运用控制语句编程
水仙花数
#include<stdio.h>
int p(int a,int b);
int main()
{
int N;
scanf(“%d”,&N);
for(int i=p(10,N-1);i<p(10,N);i++)
{
int temp = i;
int sum = 0;
while(temp>0){
sum = sum + p(temp%10, N);
temp = temp/10;
}
if(sum==i)
{
printf(“%d\n”,sum);
}
}
return 0;

}
int p(int a,int b){
int pow=1,j;
for(j=1;j<=b;j++)
{
pow=pow*a;
}
return pow;
}
7-2 猜数字游戏
猜数字游戏是令游戏机随机产生一个100以内的正整数,用户输入一个数对其进行猜测,需要你编写程序自动对其与随机产生的被猜数进行比较,并提示
#include <stdio.h>
int main()
{
int number, N, i = 0, x;
scanf(“%d %d”, &number, &N);
do
{
i++;
scanf(“%d”, &x);
if (x < 0)
printf(“Game Over”), x = number;
else if (i <= N)
{
if (x > number)
printf(“Too big\n”);
else if (x < number)
printf(“Too small\n”);
else{
if (i == 1)
printf(“Bingo!”);
else if (i <= 3)
printf(“Lucky You!”);
else
printf(“Good Guess!”);
}
}
else
printf(“Game Over”), x = number;
} while (x != number);
return 0;
}
7-3 狡猾的财主
老管家是一个聪明能干的人。他为财主工作了整整10年,财主为了让自已张目更加清楚。要求管家每天记k次账,由于管家聪明能干,因而管家总是让财主十分满意。但是由于一些人的挑拨,财主还是对管家产生了怀疑。于是他决定用一种特别的方法来判断管家的忠诚,他把每次的账目按1,2,3…编号,然后不定时的问管家问题,问题是这样的:在a到b号账中最少的一笔是多少?为了让管家没时间作假他总是一次问多个问题。
输入中第一行有两个数m,n表示有m(m<=100000)笔账,n表示有n个问题,n<=100000。
第二行为m个数,分别是账目的钱数
后面n行分别是n个问题,每行有2个数字说明开始结束的账目编号。

include

using namespace std;
int getMin(int i, int j, const int a[]);
int main(){
int m, n;
cin >> m >> n;
int *List_M = new int[m];
int a[n];
int i = 0, num;
while (cin >> num) {
List_M[i++] = num;
if (getchar() == ‘\n’) break;
}
for(int i = 0; i < n ; ++i){
int q1, q2;
cin >> q1 >> q2;
a[i] = getMin(q1, q2, List_M) ;
}
for(int el : a){
cout << el << endl;
}
delete[] List_M;
}
int getMin(int i, int j, const int a[]){
int min = a[i-1];
for(; i <= j; ++i){
if(a[i-1] < min)
min = a[i-1];
}
return min;
}

期中模拟

输出GPLT
#include
#include
using namespace std;
int main()
{
string s = “”;
cin >> s;
int n = 0;
int number[4];
char result[4] = { ‘G’,‘P’,‘L’,‘T’ };
for (int i = 0; i < 4; i++)
{
number[i] = 0;
}
char c;
c = s[0];
while ©
{
switch ©
{
case ‘G’:
case ‘g’:
number[0]++;
break;
case ‘P’:
case ‘p’:
number[1]++;
break;
case ‘L’:
case ‘l’:
number[2]++;
break;
case ‘T’:
case ‘t’:
number[3]++;
break;
default:
break;
}
n++;
c = s[n];
}
n = 1;
while (n)
{
n = 0;
for (int i = 0; i < 4; i++)
{
if (number[i])
{
cout << result[i];
n = 1;
number[i]–;
}
}
}
}
对角线二维数组
#include<stdio.h>
int main()
{
int a = 0;
int s[100][100];
int i = 0, j = 0;
scanf(“%d”, &a);
for (i = 0; i < a; i++)
{
for (j = 0; j < a; j++)
{
scanf(“%d”,& s[i][j]);
}
}

//主对角线输出
for (i = 0; i < a; i++)
{
	for (j = 0; j < a; j++)
	{
		if (i == j)
		{
			if (i == 0)
			{
				printf("%d", s[i][j]);
			}
			else printf(" %d", s[i][j]);
		}
	}
}
printf("\n");

//副对角线输出
int c = a - 1;
j = 0;
while(c>=0)//最后一行开始
{
	while(j < a)
	{
		if (c == a - 1)
		{
			printf("%d", s[c][j]);
		}
		else printf(" %d", s[c][j]);
		j++;
		break;
	}
	c--;
}

}

  1. 出租(电话号),2.出生年与3.找鞍点
    #include<bits/stdc++.h>
    #define len 11
    using namespace std;

int a[10]; //若出现,则置1

int main() {

string s; cin>>s;

int sum = 0; 			//统计号码中不同数字的个数 
for(int i = 0; i < len; i++) 
	a[(int)(s[i]-'0')] = 1;  


//这段代码为b数组赋值 
vector<int>b;
int j = 0; 
for(int i = 9; i >= 0; i--) if(a[i] == 1) b.push_back(i);	//为b数组赋值 

 
int c[len];		//存放数字对应的位数 
for(int i = 0; i < len; i++) {
	int k = ((int)(s[i]-'0'));
	for(int j = 0; j < b.size(); j++) {
		if(b[j] == k) c[i] = j; 
	}
}

//输出b数组 
cout << "int[] arr = new int[]{";
for(int i = 0; i < b.size(); i++) {
	if(i != 0) cout << ',';
	cout << b[i];
}
cout << "};" << '\n';


//输出c数组 
cout << "int[] index = new int[]{";
for(int i = 0; i < len; i++) {
	if(i != 0) cout << ',';
	cout << c[i];
}
cout << "};";

return 0; }
以上是新浪微博中一奇葩贴:“我出生于1988年,直到25岁才遇到4个数字都不相同的年份。”也就是说,直到2013年才达到“4个数字都不相同”的要求。本题请你根据要求,自动填充“我出生于y年,直到x岁才遇到n个数字都不相同的年份”这句话。

include<stdio.h>

int main()
{
int m,n,i,j=0,t,count,ch2[4];
scanf(“%d%d”,&m,&n);
for(t=m; ;m++,j++)
{
int ch1[10]={0}; //对元素初始化
count=0;t=m;
for(i=0;i<4;i++)
{
ch1[t%10]=1; //数字出现则为1
ch2[i]=t%10;
t/=10;
}
for(i=0;i<10;i++) //判断出现数的个数
{
if(ch1[i])
count++;
}
if(countn) //判断是否结束
break;
}
printf(“%d %d%d%d%d”,j,ch2[3],ch2[2],ch2[1],ch2[0]);
return 0;
}
输出在一行中按照“行下标 列下标”(下标从0开始)的格式输出鞍点的位置。如果鞍点不存在,则输出“NONE”。题目保证给出的矩阵至多存在一个鞍点。
#include <stdio.h>
int main()
{
int a[6][6],n;
scanf(“%d”,&n);
int i,j;
for(i=0; i<n; i++)
for(j=0; j<n; j++)
{
scanf(“%d”,&a[i][j]);
}
int k=0,y=0,flag=1,p=0;
if(n
1)
printf(“0 0”);
else
{
for(i=0; i<n; i++)
{
y=i;
for(p=0; p<n; p++)
{
if(a[i][k]<=a[i][p])
{
k=p;
}
}
for(j=0; j<n; j++)
{
if(a[y][k]>a[j][k])
{
y=j;
break;
}
}
if(iy)
{
flag=0;
break;
}
}
if(flag
0)
printf(“%d %d”,i,k);
else
printf(“NONE”);
}
return 0;
}
第一次试验:熟悉开发工具
字符串中小写字母变为大写字母
#include
#include
using namespace std;
int main(){
string a;
getline(cin,a);
for(int i=0;i<a.length();i++){
char c=a.at(i);
if(c>=‘a’&&c<=‘z’){
a.at(i)=c-‘a’+‘A’;
}

}
cout<<a<<endl;
return 0;

}

  • 16
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值