2005年北理复试上机题目

1、给定一个程序,关于字符串的,要求输入并调试,说出此程序的意图。意图是按字母顺序对两个字符串比较排序。第二问要求用尽可能少的语句对该程序进行修改,使其能够对两个字符串比较长度排序。

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

void main()
{
    string str1, str2;
    cout << "请输入两个字符串:";
    cin >> str1 >> str2;
    if (str1.length() >= str2.length())
        cout << str1 << str2 << endl;
    else
        cout << str2 << str1 << endl;
}

2、编写一个日期类,要求按 xxxx-xx-xx 的格式输出日期,实现加一天的操作,不考虑闰年问题,所有月份设为 30 天。本题黑盒测试时,输入 2004 年 3 月 20日,得到加一天后时间为 2004-3-21 ,能得一部分分数。输入 2004 年 3 月 30 日,得到加一天后时间为2004-4-1,能得一部分分数。输入 2004 年 12 月 30日,得到加一天后时间为 2005-1-1 ,且有时间越界处理,能得全部分数。本题满分 30。

#include<iostream>
using namespace std;

class Date
{
private:
    int y, m, d;
public:
    Date(int yy, int mm, int dd) :y(yy), m(mm), d(dd) {};
    void show()
    {
        d++;
        if (d > 30)
        {
            d = 1;
            m++;
            if (m > 12)
            {
                y++;
                m = 1;
            }
        }
        cout << "加一天后的日期是: " << y << "-" << m << "-" << d << endl;
    }
};

int main()
{
    int y, m, d;
    printf("请输入待检测的日期:");
    cin >> y >> m >> d;
    Date da(y, m, d);
    da.show();
    return 0;
}

3.编写一个复数类,要求有 4 条。一是有构造函数能对复数初始化。二是对复数 c1 ,c2 ,c3..... 能实现连加运算,令c=c1+c2+c3+..... 此处可以重载加法操作符。三是有函数实现两个复数相加,并按照 a+ib的形式输出。四是能实现对一个复数 c=a+ib,定义 double x=c 有效,使 x 的值为实部和虚部之和。本题满分 50。

#include<iostream>
using namespace std;

class Complex
{
private:
    int r, i;
public:
    Complex() { r = 0, i = 0; }
    Complex(int rr, int ii) :r(rr), i(ii) {}
    Complex operator +(Complex &x)
    {
        Complex t(r + x.r, i + x.i);
        return t;
    }
    void show()
    {
        cout << r << "+" << i << "i" << endl;
    }
    void add(Complex &x)
    {
        r += x.r;
        i += x.i;
    }
    operator double()
    {
        return (double)(r + i);
    }
};

int main()
{
    Complex c1(1, 1);
    Complex c2(2, 2);
    Complex c3(3, 3);
    Complex c = c1 + c2 + c3;
    c.show();
    c.add(c1);
    c.show();
    double x = c;
    cout << x << endl;
    return 0;
}

 

posted @ 2019-08-12 16:44  郭怡柔  阅读(122)  评论(0)    收藏  举报