#include <iostream>
using namespace std;
// 定义一个简单的函数,用于输出问候语
void greet() {
cout << "Hello, C++!" << endl;
}
int main() {
// 输出一条欢迎信息
cout << "Welcome to C++ programming!" << endl;
// 调用函数greet
greet();
// 定义一个整数变量并赋值
int num = 42;
cout << "The number is: " << num << endl;
// 使用if-else语句进行条件判断
if (num > 0) {
cout << "The number is positive." << endl;
} else if (num < 0) {
cout << "The number is negative." << endl;
} else {
cout << "The number is zero." << endl;
}
// 使用for循环打印从1到5的数字
for (int i = 1; i <= 5; ++i) {
cout << "Number: " << i << endl;
}
return 0;
}
头文件和命名空间:
#include <iostream>:包含输入输出流库。using namespace std;:使用标准命名空间,避免每次调用标准库中的对象时都要加前缀 std::。函数定义:
void greet():定义了一个名为 greet 的函数,该函数没有返回值(void),并在其中输出了一条问候语。主函数:
int main():程序的入口点。所有C++程序都从这里开始执行。cout:用于输出内容到控制台。endl:换行符,并刷新输出缓冲区。变量定义与赋值:
int num = 42;:定义一个整型变量 num 并赋值为 42。条件判断:
if-else 语句根据 num 的值输出不同的信息。循环结构:
for 循环从 1 打印到 5。这个代码示例展示了C++中一些基本的概念和语法,包括函数定义、变量定义、条件判断和循环结构。
上一篇:vector c++ 用法
下一篇:c++ map
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站