C++有许多经典的程序示例,以下是其中一些简单但常见的例子,以帮助你更好地了解C++语言的基本概念。
1. **Hello World程序:**
“`cpp
#include <iostream>
int main() {
std::cout << “Hello, World!” << std::endl;
return 0;
}
“`
2. **计算器程序:**
“`cpp
#include <iostream>
int main() {
double num1, num2, result;
char op;
std::cout << “Enter first number: “;
std::cin >> num1;
std::cout << “Enter operator (+, -, *, /): “;
std::cin >> op;
std::cout << “Enter second number: “;
std::cin >> num2;
switch(op) {
case ‘+’:
result = num1 + num2;
break;
case ‘-‘:
result = num1 – num2;
break;
case ‘*’:
result = num1 * num2;
break;
case ‘/’:
if(num2 != 0)
result = num1 / num2;
else {
std::cout << “Error! Division by zero.” << std::endl;
return 1; // Exit with an error code
}
break;
default:
std::cout << “Error! Invalid operator.” << std::endl;
return 1; // Exit with an error code
}
std::cout << “Result: ” << result << std::endl;
return 0;
}
“`
3. **循环程序:**
“`cpp
#include <iostream>
int main() {
for (int i = 1; i <= 5; ++i) {
std::cout << “Iteration ” << i << std::endl;
}
return 0;
}
“`
4. **数组和循环:**
“`cpp
#include <iostream>
int main() {
const int size = 5;
int numbers[size] = {1, 2, 3, 4, 5};
std::cout << “Array elements: “;
for (int i = 0; i < size; ++i) {
std::cout << numbers[i] << ” “;
}
std::cout << std::endl;
return 0;
}
“`
当然,接下来是一些稍微复杂一点的C++程序,涉及到函数、类和文件操作等方面: