一、简介:这里提供了20个C++有趣的实例,涵盖了基本算法、数据结构与一些LeetCode上常考的编程题。希望这些实例能够帮助您加深对C++的理解,并在实践中不断提高自己。
1. 打印"Hello World!":
cpp
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!" << endl;
return 0;
}
2. 斐波那契数列:
cpp
#include <iostream>
using namespace std;
int fib(int n) {
if (n <= 1) return n;
return fib(n-1) + fib(n-2);
}
int main() {
for (int i = 0; i < 10; i++) {
cout << fib(i) << " ";
}
cout << endl;
return 0;
}
3. 阶乘:
cpp
#include <iostream>
using namespace std;
int fact(int n) {
if (n == 0) return 1;
return n * fact(n-1);
}
int main() {
for (int i = 0; i < 10; i++) {
cout << i << "! = " << fact(i) << endl;
}
return 0;
}
4. 素数判断:
cpp
#include <iostream>
using namespace std;
bool isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i < n; i++) {
if (n % i == 0) return false;
}
return true;
}
int main() {
for (int i = 0; i < 100; i++) {
if (isPrime(i)) cout << i << " ";
}
cout << endl;
return 0;
}
5. 字符串反转:
cpp
#include <iostream>
#include <string>
using namespace std;
string reverse(string str) {
int n = str.length();
for (int i = 0; i < n/2; i++) {
swap(str[i], str[n-i-1]);
}
return str;
}
int main() {
string s