C++试听课

演示如何编写一个简单的C++程序

1. Hello World 程序
cpp
复制代码
#include <iostream>  
  
int main() {  
    std::cout << "Hello, World!" << std::endl;  
    return 0;  
}
2. 交换两个数的值
cpp
复制代码
#include <iostream>  
  
void swap(int& a, int& b) {  
    int temp = a;  
    a = b;  
    b = temp;  
}  
  
int main() {  
    int x = 5, y = 10;  
    std::cout << "Before swap: x = " << x << ", y = " << y << std::endl;  
    swap(x, y);  
    std::cout << "After swap: x = " << x << ", y = " << y << std::endl;  
    return 0;  
}
3. 计算两个数的和
cpp
复制代码
#include <iostream>  
  
int add(int a, int b) {  
    return a + b;  
}  
  
int main() {  
    int num1 = 5, num2 = 10;  
    int sum = add(num1, num2);  
    std::cout << "The sum of " << num1 << " and " << num2 << " is " << sum << std::endl;  
    return 0;  
}
4. 判断一个数是否为偶数
cpp
复制代码
#include <iostream>  
  
bool isEven(int num) {  
    return num % 2 == 0;  
}  
  
int main() {  
    int num = 10;  
    if (isEven(num)) {  
        std::cout << num << " is even." << std::endl;  
    } else {  
        std::cout << num << " is odd." << std::endl;  
    }  
    return 0;  
}
5. 使用循环打印数字 1 到 10
cpp
复制代码
#include <iostream>  
  
int main() {  
    for (int i = 1; i <= 10; ++i) {  
        std::cout << i << std::endl;  
    }  
    return 0;  
}
6. 计算阶乘
cpp
复制代码
#include <iostream>  
  
int factorial(int n) {  
    int result = 1;  
    for (int i = 2; i <= n; ++i) {  
        result *= i;  
    }  
    return result;  
}  
  
int main() {  
    int num = 5;  
    int fact = factorial(num);  
    std::cout << num << "! = " << fact << std::endl;  
    return 0;  
}
7. 字符串连接
cpp
复制代码
#include <iostream>  
#include <string>  
  
int main() {  
    std::string str1 = "Hello, ";  
    std::string str2 = "World!";  
    std::string str3 = str1 + str2;  
    std::cout << str3 << std::endl;  
    return 0;  
}
8. 数组求和
cpp
复制代码
#include <iostream>  
  
int main() {  
    int arr[] = {1, 2, 3, 4, 5};  
    int sum = 0;  
    int size = sizeof(arr) / sizeof(arr[0]);  
    for (int i = 0; i < size; ++i) {  
        sum += arr[i];  
    }  
    std::cout << "Sum of array elements: " << sum << std::endl;  
    return 0;  
}
0.052492s