C++ 学习中心
从基础到高级竞赛编程,掌握 C++ 编程
精选示例
Hello World - Your First C++ Program
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
return 0;
}This is the classic 'Hello World' program. It demonstrates the basic structure of a C++ program including headers, main function, and output.
Variables and Data Types
#include <iostream>
using namespace std;
int main() {
// Different data types
int age = 25;
double price = 99.99;
char grade = 'A';
string name = "Alice";
bool isStudent = true;
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Grade: " << grade << endl;
cout << "Price: $" << price << endl;
cout << "Is Student: " << (isStudent ? "Yes" : "No") << endl;
return 0;
}This example shows the fundamental data types in C++: int, double, char, string, and bool. Understanding these types is crucial for C++ programming.
Simple Array Operations
#include <iostream>
using namespace std;
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
cout << "Array elements:" << endl;
for(int i = 0; i < 5; i++) {
cout << "numbers[" << i << "] = " << numbers[i] << endl;
}
// Calculate sum
int sum = 0;
for(int i = 0; i < 5; i++) {
sum += numbers[i];
}
cout << "Sum of all elements: " << sum << endl;
cout << "Average: " << (double)sum / 5 << endl;
return 0;
}Arrays are fundamental data structures. This example demonstrates array declaration, initialization, iteration, and basic operations like calculating sum and average.