C++ 是一种通用、过程式、面向对象、编译式的编程语言,由 Bjarne Stroustrup 在 1980 年代初期开发,作为 C 语言的一个扩展。C++ 提供了比 C 语言更丰富的功能,特别是它支持面向对象编程(OOP),包括类、封装、继承和多态等特性。
C++ 的应用场景非常广泛,几乎涵盖了所有需要高性能和直接硬件访问的领域。以下是一些 C++ 的主要应用场景:
C++ 作为一种通用编程语言,具有许多优势,这些优势使其在多个领域,包括系统编程、游戏开发、嵌入式系统、高性能计算和科学计算等中得到了广泛应用。以下是 C++ 的一些主要优势:
std::vector
、std::map
)和算法。当学习C++编程时,案例代码是理解和掌握基础概念与语法的有效方式。以下是一些简单的C++案例代码,旨在帮助初学者逐步理解C++的基本结构和功能:
#include
using namespace std;
int main() {
cout << "Hello, World!" << endl;
return 0;
}
#include
using namespace std;
int main() {
int a, b, sum;
cout << "输入一个数: ";
cin >> a;
cout << "再次输入一个数: ";
cin >> b;
sum = a + b;
cout << a << " + " << b << " = " << sum << endl;
return 0;
}
#include
using namespace std;
int main() {
int a;
cout << "输入一个数: ";
cin >> a;
if (a % 2 == 0) {
cout << a << "为偶数";
} else {
cout << a << "为奇数";
}
cout << endl;
return 0;
}
#include
using namespace std;
int main() {
int year;
cout << "输入一个年份: ";
cin >> year;
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
cout << year << "为闰年";
} else {
cout << year << "不是闰年";
}
cout << endl;
return 0;
}
#include
using namespace std;
int main() {
int a, i;
cout << "请输入一个整数: ";
cin >> a;
for (i = 2; i < a; i++) {
if (a % i == 0) {
break;
}
}
if (i >= a) {
cout << a << "是质数";
} else {
cout << a << "不是质数";
}
cout << endl;
return 0;
}
#include
using namespace std;
int main() {
int n, sum = 1;
cout << "输入阶数: ";
cin >> n;
for (int i = 1; i <= n; i++) {
sum = sum * i;
}
cout << n << "的阶乘为" << sum << endl;
return 0;
}
#include
using namespace std;
int main() {
int n, i, t, a1 = 1, a2 = 1;
cout << "请输入项数: ";
cin >> n;
cout << a1 << endl;
cout << a2 << endl;
for (i = 3; i <= n; i++) {
t = a1 + a2;
cout << t << endl;
a1 = a2;
a2 = t;
}
return 0;
}
#include
#include // 用于 clock() 和 CLOCKS_PER_SEC
#include
int main() {
cout << "Enter the delay time, in seconds: ";
int secs;
cin >> secs;
clock_t start = clock();
while (clock() - start < secs * CLOCKS_PER_SEC);
cout << "done!\n";
return 0;
}