根据老师的文档写第一个C++实验
一、问题一
打印“Hello world”
代码如下
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World!" << endl;
system("pause");
return 0;
}
效果如下
二、问题二
编写打印菱形的程序
代码如下
#include <iostream>
using namespace std;
int main() {
while (1)
{
int N;
cin >> N;
//上半部分
for (int i = 0; i < N; i++) {
for (int j = 0; j < N - 1 - i; j++) {
cout << " ";
}
for (int j = 0; j < 2 * i + 1; j++) {
cout << "*";
}
cout << "\n";
}
//下半部分
for (int i = 0; i < N - 1; i++) {
for (int j = 0; j <= i; j++) {
cout << " ";
}
for (int j = 0; j < 2 * (N - i - 1) - 1; j++) {
cout << "*";
}
cout << "\n";
}
}
return 0;
}
效果如下
三、问题三
声明一个表示学生的结构体,学生信息包括:学号、姓名、专业、成绩;提示用户输入学生的信息,然后完整地输出出来。
代码如下
#include <iostream>
using namespace std;
//声明一个类,其中包括学生学号、姓名、专业、成绩;
struct {
int number,score;
string name,major;
}Stu[1001];
int main()
{
cout << "请输入学生学号";
cin >> Stu->number;
cout << "请输入学生姓名";
cin >> Stu->name;
cout << "请输入学生专业";
cin >> Stu->major;
cout << "请输入学生成绩";
cin >> Stu->score;
cout << "这个学生的学号是:" << Stu->number<<endl;
cout << "这个学生的姓名是:" << Stu->name << endl;
cout << "这个学生的专业是:" << Stu->major<< endl;
cout << "这个学生的成绩是:" << Stu->score << endl;
system("pause");
return 0;
}
效果如下
重新看了看题目,发现是用类而不是用结构体,所以重新写了一份
代码如下
#include <iostream>
#include <string>
using namespace std;
//声明一个类,其中包括学生学号、姓名、专业、成绩;
class Student {
public:
string name;
string major;
int score;
int number;
};
int main()
{
Student student;
cout << "请输入学生姓名:" << endl;
cin >> student.name;
cout << "请输入学生学号:" << endl;
cin >> student.number;
cout << "请输入学生专业:" << endl;
cin >> student.major;
cout << "请输入学生成绩:" << endl;
cin >> student.score;
cout << "\n";
cout << "这个叫" << student.name << "的同学,学号是"
<< student.number << "。他的专业是" << student.major
<< ",在考试中取得了" << student.score << "的成绩" << endl;
}
效果如下