编程题 #1
来源: POJ (Coursera声明:在POJ上完成的习题将不会计入Coursera的最后成绩。)
注意: 总时间限制: 1000ms 内存限制: 65536kB
描述
下面程序的输出是:
3+4i
5+6i
请补足Complex类的成员函数。不能加成员变量。
输入
无
输出
3+4i
5+6i
样例输入
样例输出
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class Complex {
private:
double r, i;
public:
void Print() {
cout << r << "+" << i << "i" << endl;
}
Complex(double r1 = 0, double r2 = 0) :r(r1), i(r2) {};
Complex &operator=(const char *s) {
string str=s;
int pos = str.find("+", 0);
string sTmp = str.substr(0, pos);
r = atof(sTmp.c_str());
sTmp = str.substr(pos + 1, str.length() - pos - 2);
i = atof(sTmp.c_str());
return *this;
}
// 在此处补充你的代码
};
int main() {
Complex a;
a = "3+4i"; a.Print();
a = "5+6i"; a.Print();
return 0;
}
编程题 #2
来源: POJ (Coursera声明:在POJ上完成的习题将不会计入Coursera的最后成绩。)
注意: 总时间限制: 1000ms 内存限制: 65536kB
描述
下面的MyInt类只有一个成员变量。MyInt类内部的部分代码被隐藏了。假设下面的程序能编译通过,且输出结果是:
4,1
请写出被隐藏的部分。(您写的内容必须是能全部放进 MyInt类内部的,MyInt的成员函数里不允许使用静态变量)。
输入
无
输出
4,1
样例输入
样例输出
#include <iostream>
using namespace std;
class MyInt {
int nVal;
public:
MyInt(int n) { nVal = n; }
int ReturnVal() { return nVal; }
// 在此处补充你的代码
MyInt& operator-(int n) {
nVal -= n;
return *this;
}
};
int main() {
MyInt objInt(10);
objInt - 2 - 1 - 3;
cout << objInt.ReturnVal();
cout << ",";
objInt - 2 - 1;
cout << objInt.ReturnVal();
return 0;
}
编程题 #3
来源: POJ (Coursera声明:在POJ上完成的习题将不会计入Coursera的最后成绩。)
注意: 总时间限制: 1000ms 内存限制: 65536kB
描述
写一个二维数组类 Array2,使得下面程序的输出结果是:
0,1,2,3,
4,5,6,7,
8,9,10,11,
next
0,1,2,3,
4,5,6,7,
8,9,10,11,
程序:
输入
无
输出
0,1,2,3,
4,5,6,7,
8,9,10,11,
next
0,1,2,3,
4,5,6,7,
8,9,10,11,
样例输入
样例输出
#include <iostream>
#include <cstring>
using namespace std;
// 在此处补充你的代码
class Array2 {
private:
int * a;
int i, j;
public:
Array2() { a = NULL; }
Array2(int i_, int j_) {
i = i_;
j = j_;
a = new int[i*j];//分配内存空间
}
Array2(Array2 &t) {
i = t.i;
j = t.j;
a = new int[i * j];
memcpy(a, t.a, sizeof(int)*i*j);//复制构造函数(可以不写)
}
Array2 & operator=(const Array2 &t) {//重载赋值
if (a != NULL) delete[]a;
i = t.i;
j = t.j;
a = new int[i*j];
memcpy(a, t.a, sizeof(int)*i*j);
return *this;
}
~Array2() { if (a != NULL) delete[]a; }
// 将返回值设为int的指针,则可以应用第二个【】,不用重载第二个【】操作符
int *operator[](int i_) {
return a + i_*j;
}
int &operator()(int i_, int j_) {
return a[i_*j + j_];
}
};
int main() {
Array2 a(3, 4);
int i, j;
for (i = 0; i < 3; ++i)
for (j = 0; j < 4; j++)
a[i][j] = i * 4 + j;
for (i = 0; i < 3; ++i) {
for (j = 0; j < 4; j++) {
cout << a(i, j) << ",";
}
cout << endl;
}
cout << "next" << endl;
Array2 b; b = a;
for (i = 0; i < 3; ++i) {
for (j = 0; j < 4; j++) {
cout << b[i][j] << ",";
}
cout << endl;
}
return 0;
}
编程题#4:大整数的加减乘除
来源: POJ (Coursera声明:在POJ上完成的习题将不会计入Coursera的最后成绩。)
注意: 总时间限制: 1000ms 内存限制: 65536kB
描述
给出两个正整数以及四则运算操作符(+ - * /),求运算结果。
输入
第一行:正整数a,长度不超过100
第二行:四则运算符o,o是“+”,“-”,“*”,“/”中的某一个
第三行:正整数b,长度不超过100
保证输入不含多余的空格或其它字符
输出
一行:表达式“a o b”的值。
补充说明:
1. 减法结果有可能为负数
2. 除法结果向下取整
3. 输出符合日常书写习惯,不能有多余的0、空格或其它字符