《C++primerplus》第4章练习题
注:略过部分题目,修改了题设要求,实现差不多的功能
1.使用字符数组。要求用户输入姓名,等第和年龄,输出其姓名和年龄,等第降一级(即字母高一级)。
#include<iostream> using namespace std; int main() { char first_name[15]; char last_name[15]; char grade; int age; cout << "What's your first name?" << endl; cin >> first_name; cout << "What's your last name?" << endl; cin >> last_name; cout << "What letter grade do you deserve?" << endl; cin >> grade; cout << "What's your age?" << endl; cin >> age; cout << "Name:"<<last_name << "," << first_name << endl; cout << "Grade:" << char(grade + 1) << endl; cout << "Age:" << age << endl; system("pause"); }
2.使用string类;定义一个结构(如盒子)。要求用户输入盒子的材质和宽度,输出盒子的名字和体积。
#include<iostream> #include<string> using namespace std; struct box { string box_material; string box_name = "box"; double width; }; int main() { box box1; cout << "Enter the box's material:" << endl; cin >> box1.box_material; cout << "Enter the box's width(cm):" << endl; cin >> box1.width; cout << box1.box_material + box1.box_name << "." << endl; cout << "Volume:" << box1.width*box1.width*box1.width << endl; system("pause"); }