if、else 示例
#include <iostream>
using namespace std; // 命名空间定义 使用C++标识符 例如:cout
int main()
{
const int max {100};
const int min {10};
int i {0};
cout << "请输入一个 10~100 的正整数:";
cin >> i; // 输入
// && 与 || 或
if (i <= max && i >= min)
{
cout << "正常" << endl;
}
else
{
cout << "输入错误" << endl;
}
return 0;
}
switch 示例
#include <iostream>
using namespace std; // 命名空间定义 使用C++标识符 例如:cout
int main()
{
enum list_1 {a1, a2=9, a3, a4}; // 枚举类型 虽然可以赋值,但是大括号内不可直接写:字符、数字、布尔值、
// enum list_2 {a0} n1; // 枚举类型 还可以同时定义变量,但不能同时初始化
list_1 list{a4};
// 判断
switch (list)
{
case a1:
cout << "a1=" << a1 << endl;
break;
case a2:
cout << "a2=" << a2 << endl;
break;
case a3:
cout << "a3=" << a3 << endl;
break;
default:
cout << "如果不是a1、a2、a3就是 a4" << endl;
cout << "a4=" << a4 << endl;
break;
}
return 0;
}
for 循环 示例
for (循环参数初始化、循环条件成立、增量、循环体)
#include <iostream>
#include <vector>
using namespace std; // 命名空间定义 使用C++标识符 例如:cout
int main()
{
vector <int> nums {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
/*
for(int i {0}; i<nums.size(); i++) 这样是会出现警告的
警告如下:
warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
意思是 无符号整形 与 有符号的整形 最后不要进行比较
解决方法:
简单的方法避开这个经过就是使用 unsigned
*/
// for 循环格式: 初始化;执行条件;自增或自减
for(unsigned int i {0}; i<nums.size(); i++)
{
cout << nums[i] << " " << endl;
}
// 死循环
// for(;;)
// {
// cout << "1" << endl;
// }
cout << "================================" << endl;
// C++ 11标准 可用 直接遍历
int a1 [] {1, 2, 3, 4, 5};
// 可使用 auto 自动类型
for (auto i: a1)
{
cout << i << " " << endl;
}
return 0;
}
while 循环 示例
#include <iostream>
#include <vector>
using namespace std; // 命名空间定义 使用C++标识符 例如:cout
int main()
{
// 普通 while 循环
int i {1};
while(i <= 10)
{
cout <<"第"<< i <<"遍\n";
++i;
}
cout << "=====================================" << endl;
// do while 先执行一边 再进行循环条件判断
// 缺失 输入类型的判断(会出bug)
int input_char {};
do {
cout << "请输入1~3" << endl;
cout << "请输入4 退出" << endl;
cout << "=====================================" << endl;
cin >> input_char;
if (input_char == 1)
{
cout << "你输入了1" << endl;
}else if (input_char == 2)
{
cout << "你输入了2" << endl;
}else if(input_char == 3){
cout << "你输入了3" << endl;
}else
{
cout << "输出不在1~3的范围内" << endl;
};
}while (input_char != 4);
return 0;
}
强制类型转换( int 与 double)
#include <iostream>
using namespace std;
int main()
{
// 数据类型转换
char c='1';
short s='1';
int n = 1;
long l = 1;
float f = 1;
double d = 1;
int p = 0;
int cc = (int)c;
// 注意:字符 转 整形时 是有问题的
// “1”是 49
cout << cc << endl;
p = ((int)n + (int)l + (double)f);
cout << (int)p << endl;
return 0;
}
查看数据类型、自动决定类型、三元表达式、取反
与 ||
或 &&
非 !=
#include <iostream>
using namespace std;
// 查看类型
// 自动判断类型
int main()
{
int x = 10;
// 返回类型为 char
// 自动判断类型
// 三元表达式 条件 ? 成立则执行 :不成立则执行;
auto c = x >= 10 ? 'Y' : 'N';
// 查看类型
cout << typeid(c).name() << endl;
cout << c << endl;
// !() 取反 注意只能返回 0 和 1
cout << !(x == 10) << endl;
return 0;
}