1.编写并测试3*3矩阵(方阵)转置,用户输入数据,使用数组保存转置矩阵。
int a[3][3];
//用户输入
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
cin >> a[i][j];
//转置
for (int i = 0; i < 3; i++)
for (int j = 0; j < i; j++)
{
int temp;
temp = a[j][i];
a[j][i] = a[i][j];
a[i][j] = temp;
}
//显示结果
for (int i = 0; i < 3; i++)
{
cout << endl;
for (int j = 0; j < 3; j++)
cout << a[i][j]<<" ";
}
输入样例:1,2,3 输出结果:1,4,7
4,5,6 2,5,8
7,8,9 3,6,9
2.使用动态内存分配生成动态数组来重新完成矩阵转置,使用指针实现函数的功能。
//动态数组的创建
int** a = new int*[3];
for (int i = 0; i < 3; i++)
a[i] = new int[3];
数据的处理与问题一相同,输出结果也相同。
3.编程实现两个字符串的连接,使用字符数组保存字符串,不要使用系统函数。
//连接函数
void linkString(const char* head, const char* back, char* res)
{
//保存初始指针位置
char* start = res;
//将前后的字符连接
while (*head != '\0')
*res++ = *head++;
while (*back != '\0')
*res++ = *back++;
//存储字符串结束标志
*res = '\0';
//还原结果指针初始位置
res = start;
}
int main()
{
//测试样例
const char* a = "abc", *b = "defg";
char* res = new char[20];
linkString(a, b, res);
//输出结果
while (*res != '\0')
cout << *res++;
return 0;
}
输出结果:abcdefg
4.使用string类声明字符串对象,重新实现字符串连接。
//输入样例
string a = "abc", b = "defg";
//结果变量
string res;
//连接
res = a + b;
//输出结果
cout << res;
输出结果:abcdefg
5.声明一个Employee类,包括姓名、街道、城市和邮编等属性,以及changeName()和display()等函数。Display()显示姓名、街道等属性,changeName()改变对象的姓名属性,实现该类,并测试。
class Employee
{
private:
//类的所有属性
string name,
street,
city,
mail;
public:
//构造函数的实现
Employee(string name, string street = "UNKOWN", string city = "UNKOWN", string mail = "UNKOWN") :name(name), street(street), city(city), mail(mail){}
void changeName(string newName) { name = newName; }
void display();
};
//显示函数实现
void Employee::display()
{
cout << "name: " << name << endl;
cout << "street: " << street << endl;
cout << "city: " << city << endl;
cout << "mail: " << mail << endl;
}
int main()
{
Employee me("WangWei","ChangAn","BeiJing","00001");
me.display();
me.changeName("WW");
cout << endl;
me.display();
return 0;
}
6.声明包含5个元素的对象数组,每个都是Employee的对象。
Employee nameList[5];