📅  最后修改于: 2023-12-03 14:39:55.090000             🧑  作者: Mango
C++是一种通用的编程语言,具有强大的功能和广泛的应用领域。以下是一些基本的C++代码片段,涵盖了语法、流程控制和常见的编程概念。
C++中最简单的程序是打印"Hello World"到控制台。
#include <iostream>
int main() {
std::cout << "Hello World" << std::endl;
return 0;
}
C++有各种数据类型,包括整数、浮点数、字符和布尔值等。
#include <iostream>
int main() {
int num = 10; // 整数
float pi = 3.14; // 单精度浮点数
double e = 2.71828; // 双精度浮点数
char ch = 'A'; // 字符
bool flag = true; // 布尔值
std::cout << "num: " << num << std::endl;
std::cout << "pi: " << pi << std::endl;
std::cout << "e: " << e << std::endl;
std::cout << "ch: " << ch << std::endl;
std::cout << "flag: " << flag << std::endl;
return 0;
}
C++支持各种运算符,包括算术运算符、关系运算符和逻辑运算符等。
#include <iostream>
int main() {
int a = 10;
int b = 5;
int sum = a + b; // 加法
int diff = a - b; // 减法
int product = a * b; // 乘法
int quotient = a / b; // 除法
int remainder = a % b; // 取模
bool equalTo = (a == b); // 相等性比较
bool notEqualTo = (a != b); // 不等性比较
bool greaterThan = (a > b); // 大于比较
bool lessThan = (a < b); // 小于比较
bool logicalAnd = (a > 0 && b > 0); // 逻辑与
bool logicalOr = (a > 0 || b > 0); // 逻辑或
bool logicalNot = !(a > 0); // 逻辑非
std::cout << "sum: " << sum << std::endl;
std::cout << "diff: " << diff << std::endl;
std::cout << "product: " << product << std::endl;
std::cout << "quotient: " << quotient << std::endl;
std::cout << "remainder: " << remainder << std::endl;
std::cout << "equalTo: " << equalTo << std::endl;
std::cout << "notEqualTo: " << notEqualTo << std::endl;
std::cout << "greaterThan: " << greaterThan << std::endl;
std::cout << "lessThan: " << lessThan << std::endl;
std::cout << "logicalAnd: " << logicalAnd << std::endl;
std::cout << "logicalOr: " << logicalOr << std::endl;
std::cout << "logicalNot: " << logicalNot << std::endl;
return 0;
}
C++提供了条件语句,可根据条件执行不同的代码块。
#include <iostream>
int main() {
int num = 10;
if (num > 0) {
std::cout << "Positive number" << std::endl;
} else if (num < 0) {
std::cout << "Negative number" << std::endl;
} else {
std::cout << "Zero" << std::endl;
}
return 0;
}
C++支持不同类型的循环,如for循环和while循环。
#include <iostream>
int main() {
// for循环
for (int i = 0; i < 5; i++) {
std::cout << i << std::endl;
}
// while循环
int num = 0;
while (num < 5) {
std::cout << num << std::endl;
num++;
}
return 0;
}
以上是一些基本的C++代码片段,涵盖了C++的一些常见语法和概念。编程是一个不断学习和探索的过程,希望这些片段能对程序员们有所帮助。