北京理工大学复试上机--2005

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

bool cmp(string s1, string s2) {
    return s1.length() < s2.length();
}

bool cmp2(string s1, string s2) {
    return s1 < s2;
}

int main() {
    string s1, s2;
    while(cin >> s1 >> s2) {
        cout << "字母顺序排序:";
        if(cmp2(s1, s2)) cout << s1 << " " << s2;
        else cout << s2 << " " << s1;
        cout << endl;
        cout << "字母长度排序:";
        if(cmp(s1, s2)) cout << s1 << " " << s2;
        else cout << s2 << " " << s1;
        cout << endl;
    }
    return 0;
}
2、编写一个日期类,要求按xxxx-xx-xx 的格式输出日期,实现加一天的操作。
输入: 3个用空格隔开的整数,分别表示年月日。测试数据不会有闰年。
输出: 按xxxx-xx-xx的格式输出,表示输入日期的后一天的日期。
#include <iostream>
using namespace std;
class date
{
public:
    int day, month, year;
    void show() {
        if(day == 28 && month == 2) {
            day = 1;
            month++;
        }
        else if(day == 30 && (month == 4 || month == 6 || month == 9 || month == 11)) {
            day = 1;
            month++;
        }
        else if(day == 31 && (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)) {
            day = 1;
            month++;
        }
        else day++;
        if(month == 13) {
            month = 1;
            year++;
        }
        cout << year << "-" << month << "-" << day << endl;
    }
};

int main() {
    int y, m, d;
    while(cin >> y >> m >> d) {
        date dd;
        dd.year = y;
        dd.month = m;
        dd.day = d;
        dd.show();
    }
    return 0;
}
3、编写一个复数类,有构造函数,能对复数初始化;重载加法操作符并按a+bi 的形式输出。
#include <iostream>
using namespace std;

class fushu
{
public:
    int a1, b1, a2, b2;
    void show() {
        if(a1 + a2 == 0) {
            if(b1 + b2 == 0) cout << "0" << endl;
            else cout << b1 + b2 << "i" << endl;
        }
        else {
            if(b1 + b2 > 0) {
                cout << a1 + a2 << "+" << b1 + b2 << "i" << endl;
            }
            else if (b1 + b2 == 0) {
                cout << a1 + a2 << endl;
            }
            else cout << a1 + a2 << b1 + b2 << "i" << endl;
        }
    }
};

int main() {
    int a1, b1, a2, b2;
    fushu fs;
    while (cin >> fs.a1 >> fs.b1 >> fs.a2 >> fs.b2) {
        fs.show();
    }
    return 0;
}

PS:类的理解还是不太明白啊啊 啊啊啊 啊 啊!!!

猜你喜欢

转载自www.cnblogs.com/ache/p/12535993.html