好的,我可以帮您生成一本Markdown格式的学习笔记,主题为C++实例学习笔记。这里是一个示例:
C++ 实例学习笔记
介绍
本文档将使用 C++ 编程语言为主题,从实例的角度出发,详细介绍一些基本的C++编程知识点。
基本语法
输出语句
使用 cout
函数进行标准输出:
cppCopy Code#include <iostream>
using namespace std;
int main()
{
cout << "Hello, world!" << endl;
return 0;
}
输入语句
使用 cin
函数进行标准输入:
cppCopy Code#include <iostream>
using namespace std;
int main()
{
int num;
cout << "请输入一个整数:";
cin >> num;
cout << "输入的整数为:" << num << endl;
return 0;
}
条件语句
使用 if...else if...else
结构进行条件判断:
cppCopy Code#include <iostream>
using namespace std;
int main()
{
int score = 85;
if (score >= 90 && score <= 100) {
cout << "A" << endl;
} else if (score >= 80 && score < 90) {
cout << "B" << endl;
} else if (score >= 70 && score < 80) {
cout << "C" << endl;
} else if (score >= 60 && score < 70) {
cout << "D" << endl;
} else {
cout << "E" << endl;
}
return 0;
}
循环语句
使用 for
或 while
结构进行循环操作:
cppCopy Code#include <iostream>
using namespace std;
int main()
{
// for 循环
for (int i = 0; i < 10; i++) {
cout << i << endl;
}
// while 循环
int j = 0;
while (j < 10) {
cout << j++ << endl;
}
return 0;
}
实例
实例一:计算圆的面积和周长
cppCopy Code#include <iostream>
using namespace std;
int main()
{
const double PI = 3.14159;
double radius, area, perimeter;
cout << "请输入圆的半径:";
cin >> radius;
area = PI * radius * radius;
perimeter = 2 * PI * radius;
cout << "圆的面积为:" << area << endl;
cout << "圆的周长为:" << perimeter << endl;
return 0;
}
实例二:随机生成并输出数列
cppCopy Code#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(NULL)); // 初始化随机种子
for (int i = 0; i < 10; i++) {
cout << rand() % 100 << " ";
}
cout << endl;
return 0;
}
实例三:排序算法
cppCopy Code#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<int> nums{1, 4, 2, 8, 5, 7};
sort(nums.begin(), nums.end());
for (auto num : nums) {
cout << num << " ";
}
cout << endl;
return 0;
}
总结
通过这些实例,我们学习了 C++ 的基本语法和一些常用的算法。希望能对您的学习有所帮助。