C++PTA错题集

目录

判断题

单选题

函数题

1.学生排名表(析构函数)

2.对象指针与对象数组(拉丁舞)

3.一个简单的队列类模板

4.学生成绩的输入和输出(运算符重载)

5.矩阵与向量的乘法

编程题

1.计算三角形面积

2.字符串替换

3. 求解给定字符串的前缀

4. 分离目录路径和文件名

5.查找电话号码

 6.Score Processing

7.数字格式异常


判断题

1.函数的参数个数和类型都相同,只是返回值不同,这不是重载函数。( T )

2.对象数组生命期结束时,对象数组的每个元素的析构函数并不会都被调用。( F )

3.静态成员变量的访问控制权限没有意义,静态成员变量均作为公有成员使用。(F)

4.如果A是B的友元类,那么B的成员函数可以访问A的私有成员。(F)

【解析】如果A是B的友元类,那么 A 的成员函数可以访问 B 的私有成员。

5.静态数据成员不属于某个对象,在给对象分配存储空间时,不包括静态数据成员所占的空间。(T)

6.在protected保护继承中,对于垂直访问等同于公有继承,对于水平访问等同于私有继承。(T)

【解析】派生类的对象基类访问为水平访问,称派生类的派生类基类的访问为垂直访问。

7.A has-a relationship is implemented via inheritance.(F)

8.类的组合关系可以用“Has-A”描述;类间的继承与派生关系可以用“Is-A”描述。(T)

9.In C++, only existing operators can be overloaded.(T)

10.对每个可重载的运算符来讲,它既可以重载为友元函数,又可以重载为成员函数,还可以重载为非成员函数。(F)

11.对单目运算符重载为友元函数时,可以说明一个形参。而重载为成员函数时,不能显式说明形参。(T)

12.重定义虚函数的派生类必须是公有继承的。(T)

13.Dynamic binding is used as default binding method in C++.(F)

【翻译】动态绑定在C++中用作默认绑定方法。

【解析】动态绑定是在运行期间发生的绑定,发生动态绑定的函数的运行版本由传入的实际参数类型决定,在运行时觉得函数的版本,所以动态绑定又称运行时绑定,动态绑定是C++的多态实现的一种形式。

在C++中,当使用基类的引用或指针调用一个虚函数时将发生动态绑定。

14.预定义的插入符从键盘上接收数据是不带缓冲区的。(F)

15.记录流的当前格式化状态标志字中的每一位用于记录一种格式,这种格式是不能被设置或清除的。(F)

16.seekg()函数和seekp()函数分别用来定位读指针和写指针的。如果使用seek()函数可以同时定义读写指针。(F)

【解析】seekp 可用于将信息 put(放入 写入)到文件。 seekg 则可用于从文件中 get(获取)信息。

单选题

1.重载函数在调用时选择的依据中,错误的是( D )。

        A.函数的参数

        B.参数的类型

        C.函数的名字

        D.函数的类型

        解析:函数类型就是函数返回值

2.以下程序存在的问题是:(   C   )

void fun()
{
 int *num1, *num2;
 num1 = new int[10];
 num2 = new int[20];
 num1[0] = 100;
 num2[0] = 300;
 num1 = num2;
 delete [] num1;
}

        A.num2不能给num1赋值

        B.num2最初指向的空间没有释放

        C.num1最初指向的空间没有释放

        D.程序没有问题

3.如果默认参数的函数声明为“ void fun(int a,int b=1,char c='a',float d=3.2);”,
则下面调用写法正确的是(  B  )。

        A.fun();

        B.fun(2,3);

        C.fun(2, ,'c',3.14)

        D.fun(int a=1);

4.在面向对象的软件系统中,不同类对象之间的通信的一种构造称为___D____。

        A.属性

        B.封装

        C.类

        D.消息

5.下列关于this指针的叙述中,正确的是(  D  )

        A.任何与类相关的函数都有this指针

        B.类的成员函数都有this指针

        C.类的友元函数都有this指针

        D.类的非静态成员函数才有this指针

6.A function that is associated with an individual object is called __________.

        A.a static function

        B.a class function

        C.an instance function   ---- 实例函数

        D.an object function

7. 下面关于友元的描述中,错误的是:( D )

        A.友元函数可以访问该类的私有数据成员

        B.一个类的友元类中的成员函数都是这个类的友元函数

        C.友元可以提高程序的运行效率

        D.类与类之间的友元关系可以继承

8.若有下面的语句:

string s="Hello";
s.append("123");
cout << s.at(5) << endl;

则执行后程序的输出结果是(  B  )

        A.o

        B.1

        C.2

        D.3

9.下列String类的(  B  )方法返回指定字符串的一部分。

        A.extractstring()

        B.substring()

        C.Substring()

        D.Middlestring()

10.建立派生类对象时, 3种构造函数分别是a(基类的构造函数)、b(成员对象的构造函数)、c(派生类的构造函数),这3种构造函数的调用顺序为(A)

        A.abc

        B.acb

        C.cab

        D.cba

【解析】对象创建时代码的加载顺序为:静态代码 --> 非静态代码 --> 构造方法。

若继承了父类,则加载顺序为:父类的静态的代码 --> 子类的静态的代码 --> 父类内部非静态代码 --> 父类的构造方法 --> 子类的非静态代码 --> 子类的构造方法。

11.为了能出现在赋值表达式的左右两边,重载的"[]"运算符应定义为:(  B  )

        A.A operator [ ] (int);

        B.A& operator [ ] (int);

        C.const A operator [ ] (int);

        D.以上答案都不对

虚函数(12-14)

12.关于纯虚函数和抽象类的描述中,(  C  )是错误的。

        A.纯虚函数是一种特殊的虚函数,它没有具体的实现

        B.抽象类是指具有纯虚函数的类

        C.一个基类中说明有纯虚函数,该基类的派生类一定不再是抽象类

        D.抽象类只能作为基类来使用,其纯虚函数的实现由派生类给出

【知识】

1.虚函数

        定义一个函数为虚函数,不代表函数为不被实现的函数。定义他为虚函数是为了允许用基类的指针来调用子类的这个函数。

2.纯虚数

        定义一个函数为纯虚函数,才代表函数没有被实现。定义纯虚函数是为了实现一个接口,起到一个规范的作用,规范继承这个类的程序员必须实现这个函数。

        纯虚函数是在基类中声明的虚函数,它在基类中没有定义,但要求任何派生类都要定义自己的实现方法。在基类中实现纯虚函数的方法是在函数原型后加 =0:

         例如:virtual void funtion1()=0

3.抽象类

  含有纯虚函数的类被称为抽象类。抽象类只能作为派生类的基类,不能定义对象,但可以定义指针。在派生类实现该纯虚函数后,定义抽象类对象的指针,并指向或引用子类对象。

1)在定义纯虚函数时,不能定义虚函数的实现部分;

2)在没有重新定义这种纯虚函数之前,是不能调用这种函数的。

13.虚析构函数的作用是(  C   )

        A.虚基类必须定义虚析构函数

        B.类对象作用域结束时释放资源

        C.delete动态对象时释放资源

        D.无意义

【解析】总的来说虚析构函数是为了避免内存泄露,而且是当子类中会有指针成员变量时才会使用得到的。也就说虚析构函数使得在删除指向子类对象的基类指针时可以调用子类的析构函数达到释放子类中堆内存的目的,而防止内存泄露的.

14.在派生类中,重载一个虚函数时,要求函数名、参数的个数、参数的类型、参数的顺序和函数的返回值  (  A  )

        A.相同

        B.不同

        C.相容

        D.部分相同

模板(15-16)

15.模板函数的真正代码是在哪个时期产生的__C__。

        A.源程序中声明函数时

        B.源程序中定义函数时

        C.源程序中调用函数时

        D.运行执行函数时

16.下列关于pair<>类模板的描述中,错误的是(  C  )

        A.pair<>类模板定义头文件utility中

        B.pair<>类模板作用是将两个数据组成一个数据,两个数据可以是同一个类型也可以是不同的类型

        C.创建pair<>对象只能调用其构造函数

        D.pair<>类模拟提供了两个成员函数first与second来访问这的两个数据

标准模板库STL(17)

17.设有如下代码段:

std::map<char *, int> m;
const int MAX_SIZE = 100;
int main() {
    char str[MAX_SIZE];
    for (int i = 0; i < 10; i++) {
        std::cin >> str;
        m[str] = i;
    }
    std::cout << m.size() << std::endl;
}

读入10个字符串,则输出的 m.size() 为(   B   )

        A.0

        B.1

        C.10

IO流与文件操作(18-21)

18.分析以下程序:程序的输出结果是(   B   )

#include <iostream>
using namespace std;
void fun(int num)
{
    cout << num << endl;
}
void fun(char ch)
{
    cout << (ch + 1) << endl;
}
int main()
{
    fun('A');
    return 0;
}

        A.65

        B.66

        C.A

        D.B

19.关于read()函数的下列描述中,正确的是( D )。

        A.该函数只能用来从键盘输入中获取字符串

        B.该函数所获取的字符多少是不受限制的

        C.该函数只能用于文本文件的操作中

        D.该函数只能按规定读取所指定的字符数

20.在C++中,打开一个文件,就是将整个文件与一个(B )建立关联,关闭一个文件,就是取消这种关联。

        A.类

        B.流

        C.对象

        D.结构

21.下列打开文件的表达式中,错误的是:(  D  )

        A.ofstream ofile; ofile.open(“C:\vc\abc.txt”,ios::binary);

        B.fstream iofile;iofile.open(“abc.txt”,ios::ate);

        C.ifstream ifile (“C:\vc\abc.txt”);

        D.cout.open(“C:\vc\abc.txt”,ios::binary);

异常处理

22.What is wrong in the following code?( C )

  vector<int> v;
  v[0] = 2.5;

        A.The program has a compile error because there are no elements in the vector.

        B.The program has a compile error because you cannot assign a double value to v[0].

        C.The program has a runtime error because there are no elements in the vector.

        D.The program has a runtime error because you cannot assign a double value to v[0].

23.The function what() is defined in ______A________.

        A.exception

        B.runtime_error

        C.overflow_error

        D.bad_exception

24.下列关于异常的描述中,错误的是(A)。

        A.编译错属于异常,可以抛出

        B.运行错属于异常

        C.硬件故障也可当异常抛出

        D.只要是编程者认为是异常的都可当异常抛出

函数题

1.学生排名表(析构函数)

现在输入一批学生(人数大于0且不超过100)的名次和他们的姓名。要求按名次输出每个人的排名。

输入格式:每行为一个学生的信息,共两项,第一项为排名(为正整数,且任意两名学生的排名均不同),第二项为学生姓名。当输入-1时,表示输入结束。

输出格式:按名次输出学生姓名,每行一个。

函数接口定义:

main函数的一部分。

裁判测试程序样例:

#include <iostream>
#include <string>
using namespace std;
class Student{
    int rank;
    string name;
    public:
        int getRank(){return rank;    }
        Student(string name, int rank):name(name), rank(rank){    }
        ~Student(){ cout<<name<<endl;}
};
int main(){
    int rank, count=0;
    const int SIZE=100;
    Student *pS[SIZE];
    string name;
    cin>>rank;
    while(count<SIZE && rank>0){
        cin>>name;
        pS[count++]= new Student(name, rank);
        cin>>rank;
    }

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

    return 0;
}

输入样例:

1 Jack
5 Peter
2 Alice
6 Kate
52 Mike
-1

输出样例:

Jack
Alice
Peter
Kate
Mike

参考:

   for(int i=1;i<count;i++){
        for(int j=0;j<count-i;j++){
          if(pS[j]->getRank()>pS[j+1]->getRank()){
            Student *temp=pS[j];
            pS[j]=pS[j+1];
            pS[j+1]=temp;

                      }
        }
    }

   for(int i=0;i<count;i++){
    delete pS[i];
   }

 或

	for(int i = 0; i < count -1; i++ ){
		for(int j = 0 ; j < count - 1 -i; j++){
			if(pS[j]->getRank() > pS[j+1]->getRank()){
				Student * temp = pS[j];
				pS[j] = pS[j+1];
				pS[j+1] = temp; 
			}
		}
	}
	
	for(int i=0;i<count;i++){
    	delete pS[i];
	}

【其他】若是编程题可以使用sort()函数(头文件#include<algorithm>)。它有三个参数sort(begin, end, cmp),其中begin为指向待sort()的数组的第一个元素的指针,end为指向待sort()的数组的最后一个元素的下一个位置的指针,cmp参数为排序准则,cmp参数可以不写,如果不写的话,默认从小到大进行排序。

部分:

bool cmp_rank(Student *x, Student *y){
	return x->getRank() < y->getRank() ;
	
}
sort(pS,pS+count,cmp_rank);

全:

#include <iostream>
#include <string>
#include<algorithm>//#include<algorithm>
using namespace std;
class Student{
    int rank;
    string name;
    public:
        int getRank(){return rank;    }
        Student(string name, int rank):name(name), rank(rank){    }
        ~Student(){ cout<<name<<endl;}
};

bool cmp_rank(Student *x, Student *y){
	return x->getRank() < y->getRank() ;
	
}
int main(){
    int rank, count=0;
    const int SIZE=100;
    Student *pS[SIZE];
    string name;
    cin>>rank;
    while(count<SIZE && rank>0){
        cin>>name;
        pS[count++]= new Student(name, rank);
        cin>>rank;
    }

/* 请在这里填写答案 */
	
	sort(pS,pS+count,cmp_rank);

	for(int i=0;i<count;i++){
    	delete pS[i];
	}

    return 0;
}

2.对象指针与对象数组(拉丁舞)

对象指针与对象数组(拉丁舞)

怡山小学毕业文艺晚会上,拉丁舞是最受欢迎的节目。不过,每年为了排练这个节目,舞蹈组都会出现一些纠纷。有些同学特别受欢迎,有些却少人问津,因此安排舞伴成为舞蹈组陈老师最头疼的问题。

为了解决这一问题,今年陈老师决定让按先男生后女生,先低号后高号的顺序,每个人先报上自己期待的舞伴,每人报两位,先报最期待的舞伴。接下来按先男生后女生,先低号后高号的顺序,依次按以下规则匹配舞伴:

(1)每个人均按志愿顺序从前到后确定舞伴。如果第一志愿匹配不成功,则考虑第二志愿。

(2)如果A的当前志愿为B,则如果B未匹配舞伴,且有以下情形之一者,A和B匹配成功:

        2a) B的期待名单中A。

        2b) B的期待名单中没有A,但B期待的两位舞伴均已匹配成功,所以B只能与A凑合。

输入时先输入男生数m, 接下来m行,第一项为学生的姓名,后两项为期待舞伴的编号,编号从0开始,最大为女生数减1。接下来输入女生数f,接下来f行,第一项为学生的姓名,后两项为期待舞伴的编号,编号从0开始,最大为男生数减1。

输出时按男生的编号顺序输出  姓名:舞伴姓名

注意两个姓名间有冒号隔开

函数接口定义:

Student的两个成员函数:
void printPair();
void addPair();    

裁判测试程序样例:

#include <iostream>
#include <string>
using namespace std;
const int K=2;
const int N=20;
class Student{
  string name;
  Student *welcome[K];
  Student *pair;
  public:
      void init(string &name, Student *a, Student *b) {
        this->name=name; 
        welcome[0]=a;
        welcome[1]=b;
        pair=NULL;
      }
     void printPair();
     void addPair();        
};

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

int main(){
    Student male[N], female[N];
    int m, f, i, j, a, b;
    string name;
    cin>>m;
    for(i=0;i<m;i++){
      cin>>name>>a>>b;
      male[i].init(name, &female[a], &female[b]);
    }
    cin>>f;
    for(i=0;i<f;i++){
      cin>>name>>a>>b;
      female[i].init(name, &male[a], &male[b]);
    }
    for(i=0;i<m;i++) male[i].addPair();
    for(i=0;i<f;i++) female[i].addPair();
    for(i=0;i<m;i++) male[i].printPair();
    return 0;
}

输入样例:

5
M0 3 1
M1 1 3
M2 1 4
M3 3 1
M4 0 3
5
F0 0 2
F1 2 0
F2 2 1
F3 2 4
F4 3 2

输出样例:

M0:F1
M2:F4
M4:F0

说明:匹配过程如下:

(1)M0先选择F3, 但F3并未期待M0;接下来M0选择F1, F1也期待M0,故匹配成功。

(2)M1选择F1, 但F1已匹配,故,不成功;M1选择F3,但F3未期待M1,仍然不成功。

(3)M2选择F1,F1已匹配;M2选择F4, F4未匹配且也期待M2,故匹配成功。

(4)M3选择F3,但F3未期待他,不成功;M3选择F1,F1已匹配,不成功。

(5)M4选择F0, F0不期待M4,但是F0期待的M0和M2已分配,所以凑合,匹配成功。

(6)F0已匹配, F1已匹配。

(7)F2选择M2, M2已匹配,不成功; F2选择M1, M1未匹配,但期待表中没有F2,且F3也未分配,故不成功。

(8)F3选择M2, M2已匹配,不成功;F3选择M4, M4已匹配,不成功。

(9)F4已匹配。

参考:

void Student::addPair(){
    if(pair == NULL &&
    (this == welcome[0]->welcome[0] || this == welcome[0]->welcome[1] )
    && welcome[0]->pair == NULL)
    {
        pair = welcome[0];
        welcome[0]->pair = this;
        return ;
    }
    if(pair == NULL && welcome[0]->pair == NULL &&
      (welcome[0]->welcome[0]->pair != NULL && welcome[0]->welcome[1]->pair != NULL))
    {
        pair = welcome[0];
        welcome[0]->pair = this;
        return ;
    }
    if(pair == NULL &&
    (this == welcome[1]->welcome[0] || this == welcome[1]->welcome[1] )
    && welcome[1]->pair == NULL)
    {
        pair = welcome[1];
        welcome[1]->pair = this;
        return ;
    }
    if(pair == NULL && welcome[1]->pair == NULL &&
      (welcome[1]->welcome[0]->pair != NULL && welcome[1]->welcome[1]->pair != NULL))
    {
        pair = welcome[1];
        welcome[1]->pair = this;
        return ;
    }
}
void Student::printPair(){
  //只输出配对成功的名单
    if(this->pair)
  cout << this->name << ":" << this->pair->name << endl;
}

3.一个简单的队列类模板

请按照下列简单的整数队列类创建一个简单的队列类模板。

整数队列类如下:

const int SIZE=100;
//整数队列类
class Queue {    
  int q[SIZE];
  int front;  //队列头
  int rear;   //队列尾
public:
  Queue( ) 
  { front = rear = 0; }
  void put(int i); // 在队尾放置一个数据
  int get( );  // 从队列头部取一个数据
};

裁判测试程序样例:

在这里给出函数被调用进行测试的例子。例如:
#include <iostream>
#include <string>
using namespace std;
// 你提交的代码将嵌入到这里

int main()
{
  Queue<int> a; // 创建一个整数队列
  int m,n;
  cin>>m>>n; 
  a.put(m);
  a.put(n);
  cout << a.get() << " ";
  cout << a.get() << endl;

  Queue<double> d; // 创建一个双精度浮点数队列
  double x,y;
  cin>>x>>y;
  d.put(x);
  d.put(y);
  cout << d.get() << " ";
  cout << d.get() << endl;

  Queue<string> qs;// 创建一个字符串队列
  string s1,s2,s3;
  cin>>s1>>s2>>s3;
  qs.put(s1);
  qs.put(s2);
  qs.put(s3);
  cout <<    qs.get() << " ";
  cout <<    qs.get() << " ";
  cout << qs.get() << endl;

  return 0;
}

输入样例:

6 9
3.14159 2.781828
ShenZhen Beijing HangZhou

输出样例:

6 9
3.14159 2.78183
ShenZhen Beijing HangZhou

参考:

const int SIZE=100;
//整数队列类
template <typename T>
class Queue {    
  T q[SIZE];
  int front;  //队列头
  int rear;   //队列尾
public:
  Queue( ) 
  { front = rear = 0; }
  void put(T i) // 在队尾放置一个数据
    {
        if(front == SIZE)
            exit(0);
        rear++;
        q[rear] = i;
    }
  T get()  // 从队列头部取一个数据
    {
        if(rear == front)
            exit(0);
        front++;
        return q[front];
    }
};

4.学生成绩的输入和输出(运算符重载)

现在需要输入一组学生的姓名和成绩,然后输出这些学生的姓名和等级。

输入时,首先要输入学生数(正整数)N。接着输入N组学生成绩,每组成绩包括两项:第一项是学生姓名,第二项是学生的成绩(整数)。

输出时,依次输出各个学生的序号(从1开始顺序编号),学生姓名,成绩等级(不小于60为PASS,否则为FAIL)

函数接口定义:

面向Student类对象的流插入和流提取运算符

裁判测试程序样例:

#include <iostream>
#include <string>
using namespace std;

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

int main(){
    int i, repeat;
    Student st;
    cin>>repeat;
    for(i=0;i<repeat;i++){
        cin>>st;
        cout<<st<<endl;
    }
    return 0;
}

输入样例:

3
Li 75
Zhang 50
Yang 99

输出样例:

1. Li PASS
2. Zhang FAIL
3. Yang PASS

参考:

class Student{
public :
    Student (string ,int);

    friend istream & operator >>(istream&,Student &);
    friend ostream & operator <<(ostream&,Student &);
private:
    string name;
    int score;
};


Student::Student( string name="def",int score=0){
    
}
istream &operator >>(istream & is ,Student &s ){
    is>> s.name>>s.score;
    return is;
}

ostream &operator <<(ostream & os ,Student &s){
    static int sum;sum=sum+1;
    os<<sum<<". "<<s.name<<" ";
    if(s.score>=60)os<<"PASS";
    else{os<<"FAIL";}

    return os;
}

【说明】

重载操作运算符 (>>    <<)只能重载为友元函数。

 friend istream & operator >>(istream&,Student &);
 friend ostream & operator <<(ostream&,Student &);

5.矩阵与向量的乘法

矩阵与向量相乘:当矩阵的列数与向量的行数相等时,用矩阵的第i行乘以向量,并输出结果向量,否则输出"Bad multiplying Matrix with Vector."。

函数接口定义:

int& Matrix::operator()(int i,int j);
ostream& operator<<(ostream& out,const Vector& x);
Vector operator*(Matrix& mat,Vector& vex);

int& Matrix::operator()(int i,int j):返回第i行第j列的矩阵元素(可作左值),应有下标越界检查,如果越界则输出信息"Matrix index out of range.";
ostream& operator<<(ostream& out,const Vector& x):将向量x输出到输出流out对象。为能达到连续输入对象的效果,设置返回类型为引用;
Vector operator*(Matrix& mat,Vector& vex):参数为矩阵mat、向量vex,返回二者的乘积。

裁判测试程序样例:

#include<iostream>
#include<cstring>
using namespace std;
class Matrix;  //类的向前声明
class Vector {
    private:
        int* v;
        int sz;
    public:
        Vector(int n) {            v=new int[sz=n];        }
        Vector(const Vector& t) {
            v=new int[sz=t.sz];
            memcpy(v,t.v,sz*sizeof(int));   //深拷贝
        }
        ~Vector() {    delete []v;    }
        int& operator[](int i) {
            if(i>=0 &&i<sz)  //下标越界检查
                return v[i];
            else {
                cout<<"Vector index out of range.\n";    exit(0);
            }
        }
        friend ostream& operator<<(ostream& out,const Vector& x);
        friend Vector operator*(Matrix& m,Vector& v);//重载乘法运算符
};
class Matrix {
    private:
        int* m;
        int szl,szr;
    public:
        Matrix(int a,int b) {
            szl=a;    szr=b;
            m=new int[a*b];   //用一维数组模拟矩阵
        }
        ~Matrix() {    delete []m;    }
        int& operator()(int i,int j) ;
        friend Vector operator*(Matrix& m,Vector& v);
};
int main() {
    int n,m;
    cin>>n>>m;
    Matrix ma(n,m);
    for(int i=0; i<n; i++)
        for(int j=0; j<m; j++)
            cin>>ma(i,j);
    cin>>n;
    Vector ve(n);
    for(int i=0; i<n; i++) cin>>ve[i];
    Vector va = ma * ve;
    cout<<va<<endl;
    return 0;
}

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

输入样例:

在这里给出一组输入。输入矩阵的行、列数n,m,其后输入矩阵的n*m个元素,接着输入向量的大小t,其后输入向量的t个元素,例如:

4 3
1 2 3
0 1 2
1 1 3
1 2 1
3
2 1 0

输出样例:

在这里给出相应的输出。例如:

4 1 3 4 

参考:

//矩阵到数组的转换输入
int& Matrix::operator()(int i,int j){
    return this->m[i*this->szr+j];
    
}
//输出向量
ostream& operator<<(ostream& out,const Vector& x){
    for(int i=0;i<x.sz;i++){
        out<<x.v[i]<<" ";
    }
    return out;
}
//乘法
Vector operator*(Matrix& mat,Vector& vex){
    //当矩阵的列数与向量的行数不相等时
    if(mat.szr!=vex.sz){
        cout<<"Bad multiplying Matrix with Vector.";
        return NULL;
    }
    Vector v(mat.szl);
    for(int i=0;i<mat.szl;i++){
        int sum=0;
        for(int j=0;j<vex.sz;j++){
            sum+=mat.m[i*mat.szr+j]*vex.v[j];
        }
        
        v.v[i]=sum;
    }
    return v;
}

编程题

1.计算三角形面积

从键盘输入三个数,用来表示三角形的三条边长。如果能构成三角形就输出三角形的面积,否则就输出No。

输入格式:

请在这里写输入三角形的三条边长,例如:
3.1 4.2 5.3

输出格式:

请在这里输出三角形的面积,例如:

6.50661

输入样例:

3.0 4.0 5.0

输出样例:

6

参考:

#include <iostream>

#include <cmath>

using namespace std;

int main(){

    double a, b, c, p, s;

    cin >> a >> b >> c;

    if(a+b<=c || a+c<=b || b+c<=a){

        cout << "No" << endl;

        return 0;

    }

    p = (a+b+c)/2;

    s = sqrt(p*(p-a)*(p-b)*(p-c));

    cout << s << endl;

    return 0;

}

【解析】先判断三角形是否存在(任意两边之和大于第三边,任意两边之差小于第三边),

               在计算三角形的面积  p = (a+b+c)/2;   s = sqrt(p*(p-a)*(p-b)*(p-c));

2.字符串替换

将文本文件中指定的字符串替换成新字符串。
由于目前的OJ系统暂时不能支持用户读入文件,我们编写程序从键盘输入文件中的内容,当输入的一行为end时,表示结束。end后面有两个字符串,要求用第二个字符串替换文本中所有的第一个字符串。

输入格式:

Xi’an Institute of Posts and Telecommunications is co-designed and implemented by the People’s Government of Shaanxi Province and the Ministry of Industry and Information Technology.
The Institute is located in Xi’an, a historic city in Northwest China, famous for its magnificent ancient culture.

end (表示结束)

Institute (第一个字符串,要求用第二个字符串替换)

University (第二个字符串)

输出格式:

Xi’an University of Posts and Telecommunications is co-designed and implemented by the People’s Government of Shaanxi Province and the Ministry of Industry and Information Technology.The University is located in Xi’an, a historic city in Northwest China, famous for its magnificent ancient culture.

输入样例:

Xi’an Institute of Posts and Telecommunications is co-designed and implemented by the People’s Government of Shaanxi Province and the Ministry of Industry and Information Technology.
The Institute is located in Xi’an, a historic city in Northwest China, famous for its magnificent ancient culture.
end
Institute
University

输出样例:

Xi’an University of Posts and Telecommunications is co-designed and implemented by the People’s Government of Shaanxi Province and the Ministry of Industry and Information Technology.The University is located in Xi’an, a historic city in Northwest China, famous for its magnificent ancient culture.

参考:

#include<iostream>
#include<cstring>
using namespace std;

int main()
{
    string str;
    string str1;
    string str2;
    string tmp;
    while(true)
    {
        getline(cin,tmp);
        if(tmp.compare("end")==0) //结束
            break;
        str.append(tmp);
        str += '\n';
    }
    getline(cin,str1);
    getline(cin,str2);
    int index = str.find(str1);

    while(index != -1)
    {
        str.replace(index,str1.length(),str2);
        index = str.find(str1,index+1);
    }
    cout<<str;
}

 【知识1】C++中getline()的用法

        getline是C++标准库函数;它有两种形式,一种是头文件< istream >中输入流成员函数;一种在头文件< string >中普通函数.

输入流成员函数getline()
        函数语法结构:

                在< istream >中的getline()函数有两种重载形式:

                        istream& getline (char* s, streamsize n );
                        istream& getline (char* s, streamsize n, char delim );

作用: 从istream中读取至多n个字符(包含结束标记符)保存在s对应的数组中。即使还没读够n个字符,如果遇到delim 或 字数达到限制,则读取终止,delim都不会被保存进s对应的数组中。

cin.getline(name, 256);
或
cin.getline( line, 100, 't' );

普通函数getline()
        函数语法结构:

                在< string >中的getline函数有四种重载形式:

                        istream& getline (istream&  is, string& str, char delim);
                        istream& getline (istream&& is, string& str, char delim);
                        istream& getline (istream&  is, string& str);
                        istream& getline (istream&& is, string& str);

函数的变量:

is :表示一个输入流,例如 cin。
str :string类型的引用,用来存储输入流中的流信息。
delim :char类型的变量,所设置的截断字符;在不自定义设置的情况下,遇到’\n’,则终止输入。

用法和上一种类似,但是读取的istream是作为参数is传进函数的。

读取的字符串保存在string类型的str中。
 

getline(cin, name);
或
getline(std::cin, name, '#');

 【知识2】find()函数

s.find(str)
        string中find()返回值是字母在母串中的下标位置。
        如果没有找到,那么会返回一个特别的标记npos,一般写作string::npos。

s.find(str,pos)
        find(str,pos)是用来寻找从pos开始(包括pos处字符)匹配str的位置。 

3. 求解给定字符串的前缀

求解给定字符串的前缀。

输入格式:

输入数目不定的多对字符串,每行两个,以空格分开。 例如:

filename filepath

Tom Jack

输出格式:

返回两个字符串的最大前缀,例如:

The common prefix is file

No common prefix

输入样例:

filename filepath
Tom Jack

输出样例:

The common prefix is file
No common prefix

参考:

#include<iostream>
#include<cstring>

using namespace std;

int main()
{
    char a[20];
    char b[20];
    int n;
    while(cin>>a)
    {
    cin>>b;
    n=(strlen(a)>strlen(b))?strlen(a):strlen(b);
    for(int i=0;i<n;i++)
    {
        if(a[i]!=b[i])
            {
            a[i]='\0';
        }
    }
        if(a[0]=='\0')
        cout<<"No common prefix"<<endl;
        else
        cout<<"The common prefix is "<<a<<endl;
}
    return 0;
 }

 【其他】若a,b变量用string定义,则输出有误。

                filename filepath会对应输出   file a   。

                将char数组中的一个元素变为 '\0',则其cout输出时从'\0'起不再输出。

                可以搜索一下char数组和string类型用cout输出的区别。

4. 分离目录路径和文件名

输入文件目录路径和文件名,要求分离成目录路径和文件名分别输出

输入格式:

例如:输入

c:\windows\winhelp.exe

输出格式:

c:\windows (目录路径)

winhelp.exe (文件名)

输入样例:

/usr/bin/man

输出样例:

/usr/bin
man

参考:

#include<iostream>
#include<string>
using namespace std;
void filename(string str)
{
	size_t found = str.find_last_of("/\\");
	cout << str.substr(0, found) << endl;
	cout << str.substr(found + 1) << endl;
}
int main()
{
	string str;
	getline(cin, str);

	filename(str);

	system("pause");
	return 0;
}

 【知识】 s.find_first_of(str)

                 s.find_last_of(str)

 s.find_first_of(str) 和 s.find_last_of(str)
找到目标字符在字符串中第一次出现和最后一次出现的位置

5.查找电话号码

文件phonebook1.txt中有若干联系人的姓名和电话号码。

高富帅 13312342222

白富美 13412343333

孙悟空 13512345555

唐三藏 13612346666

猪悟能 13712347777

沙悟净 13812348888

请你编写一个简单的通信录程序,当从键盘输入一个姓名时查找到对应的电话号码并输出。如果没找到则显示Not found.
由于目前的自动裁判系统暂时不能支持用户读入文件,我们编写程序从键盘输入文件中的姓名和电话号码,当输入的名字为noname时,表示结束。noname后面有一个名字,需要查找其对应的电话号码。

输入格式:

高富帅 13312342222

白富美 13412343333

孙悟空 13512345555

唐三藏 13612346666

猪悟能 13712347777

沙悟净 13812348888

noname (表示结束)

唐三藏 (需要查找此人的电话号码)

输出格式:

13612346666 (输出对应的电话号码)

输入样例:

白富美 13412343333
孙悟空 13512345555
唐三藏 13612346666
猪悟能 13712347777
沙悟净 13812348888
noname
白骨精

输出样例:

Not found.

 参考:

#include <iostream>
#include <string>
#include <vector>
#include <map>
using namespace std;
int main() {
    map<string, string> m;
    string a;
    string b;
    while(1) {
        cin >> a;
        if (a == "noname")
            break;
        cin >> b;
            m.insert(pair<string, string>(a, b));
    }
    map<string, string> :: iterator p;
    string s;
    cin >> s;
    p = m.find(s);
    if (p != m.end())
        cout << p -> second << endl;
    else
        cout << "Not found." << endl;
    return 0;
}

【注意】 m.insert(pair<string, string>(a, b));

 6.Score Processing

Write a program to process students score data.

The input of your program has lines of text, in one of the two formats:

  1. Student's name and student id, as <student id>, <name>, and
  2. Score for one student of one course, as <student id>, <course name>, <marks>.

Example of the two formats are:

3190101234, Zhang San
3190101111, Linear Algebra, 89.5

Comma is used as the seperator of each field, and will never be in any of the fields. Notice that there are more than one word for name of the person and name of the course. To make your code easier, the score can be treated as double.

The number of the students and the number of the courses are not known at the beginning. The number of lines are not known at the beginning either. The lines of different format appear in no order. One student may not get enrolled in every course.

Your program should read every line in and print out a table of summary in .csv format.

The first line of the output is the table head, consists fields like this:

student id, name, <course name 1>, <course name 2>, ..., average

where the course names are all the courses read, in alphabet order. There should be one space after each comma.

Then each line of the output is data for one student, in the ascended order of their student id, with score of each course, like:

3190101234, Zhang San, 85.0, , 89.5, , , 87.3

For the course that hasn't been enrolled, leave a blank before the comma, and should not get included in the average. The average has one decimal place. There should be one space after each comma.

And the last line of the output is a summary line for average score of every course, like:

, , 76.2, 87.4, , , 76.8

All the number output, including the averages have one decimal place.

Input Format

As described in the text above.

Output Format

As described in the text above.
The standard output is generated by a program compiled by gcc, that the round of the first decimal place is in the "gcc way".

Sample Input

3180111435, Operating System, 34.5
3180111430, Linear Algebra, 80
3180111435, Jessie Zhao
3180111430, Zhiwen Yang
3180111430, Computer Architecture, 46.5
3180111434, Linear Algebra, 61.5
3180111434, Anna Teng

Sample Output

student id, name, Computer Architecture, Linear Algebra, Operating System, average
3180111430, Zhiwen Yang, 46.5, 80.0, , 63.2
3180111434, Anna Teng, , 61.5, , 61.5
3180111435, Jessie Zhao, , , 34.5, 34.5
, , 46.5, 70.8, 34.5, 50.6

参考:

#include<algorithm>
#include<iostream>
#include<iomanip>
#include<cstdlib>
#include<cstdio>
#include<string>
#include<vector>
#include<set>
#include<map>
using namespace std;
class student{
	public:
		string id, name;
		map<string, double> course;
		student() : id(""), name("") {
			course.clear();
		}
		void set1(string id_, string name_) {
			id = id_;
			name = name_;
		}
		void set2(string a, double b) {
			course[a] = b;
		}
		bool operator < (const student& tmp) const {
			return id < tmp.id;
		}
};
int main() {
	string in;
	set<string> s;
	vector<student> res;
	map<string, int> mp;
	while (getline(cin, in)) {
		int n = 0;
		for (int i = 0; i < in.size(); i++) {
			if (in[i] == ',') {
				n++;
			}
		}
		switch (n) {
			case 1: {
				int ad = -1;
				for (int i = 0; i < in.size(); i++) {
					if (in[i] == ',') {
						ad = i;
						break;
					}
				}
				string id, name;
				id = in.substr(0, ad);
				name = in.substr(ad+2);
				if (!mp.count(id)) {
					mp[id] = res.size();
					student tmp;
					tmp.set1(id, name);
					res.push_back(tmp);
				} else {
					ad = mp[id];
					res[ad].set1(id, name);
				}
				break;
			}
			case 2: {
				int ad1 = -1, ad2 = -1;
				for (int i = 0; i < in.size(); i++) {
					if (in[i] == ',') {
						if (ad1 == -1) {
							ad1 = i;
						} else {
							ad2 = i;
							break;
						}
					}
				}
				string id, course, grade;
				id = in.substr(0, ad1);
				course = in.substr(ad1+2, ad2-ad1-2);
				grade = in.substr(ad2+2);
				s.insert(course);
				if (!mp.count(id)) {
					mp[id] = res.size();
					student tmp;
					tmp.set2(course, atof(grade.c_str()));
					res.push_back(tmp);
				} else {
					int ad = mp[id];
					res[ad].set2(course, atof(grade.c_str()));
				}
				break;
			}
		}
	}
	cout << "student id, name";
	for (auto i: s) {
		cout << ", " << i;
	}
	cout << ", average" << endl;
	vector<double> sum(s.size(), 0), cnt(s.size(), 0);
	sort(res.begin(), res.end());
	int tot = 0;
	double ave = 0;
	for (int i = 0; i < res.size(); i++) {
		cout << res[i].id << ", "<< res[i].name;
		int ad = 0;
		tot = 0;
		ave = 0;
		for (auto j: s) {
			cout << ", ";
			if (res[i].course.count(j)) {
				cout << fixed << setprecision(1) << res[i].course[j];
				sum[ad] += res[i].course[j];
				cnt[ad]++;
				ave += res[i].course[j];
				tot++;
			}
			ad++;
		}
		cout << ", " << fixed << setprecision(1) << ave/tot << endl;
	}
	cout << ", ";
	tot = 0;
	ave = 0;
	for (int i = 0; i < sum.size(); i++) {
		tot++;
		ave += sum[i]/cnt[i];
		cout << ", " << fixed << setprecision(1) << sum[i]/cnt[i];
	}
	cout << ", " << fixed << setprecision(1) << ave/tot << endl;
	return 0;
}

7.数字格式异常

(NumberFormatException数字格式异常)编写一个程序,提示用户读取两个整数,然后显示他们的和。程序应该在输入不正确时提示用户再次输入数字。

输入格式:

i 9 (第1次输入)
l 8 (第2次输入)
5 6 (第3次输入)

输出格式:

Incorrect input and re-enter two integers: (第1次输出提示)
Incorrect input and re-enter two integers: (第2次输出提示)
Sum is 11 (输出结果)

输入样例:

i 9
l 8
5 6

输出样例:

Incorrect input and re-enter two integers:
Incorrect input and re-enter two integers:
Sum is 11

参考:

#include <iostream>
#include<string.h>
using namespace std;
int f;
int toNumb(char co[])
{
    int len=strlen(co);
    int i;
    int sum=0;
    int w=1;
    for(i=len-1;i>=0;i--)
    {
        if(!(co[i]<='9' && co[i]>='0'))
        {
            f=1;
            return 0;
        }
        sum+=w*(co[i]-'0');
        w*=10;
    }
    return sum;
}
int main ()
{
    string a,b;
    while(1)
    {
        cin>>a>>b;
        f=0;
        int m=toNumb(&a[0]);
        int n=toNumb(&b[0]);
        if(f)
        {
            cout<<"Incorrect input and re-enter two integers:"<<endl;
            continue;
        }
        else
        {
            cout<<"Sum is "<<m+n<<endl;
            break;
        }
    }

}

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值