目录
一、C++初识
1.1、第一个程序书写
#include <iostream>
using namespace std;
int main(){
cout << "hello world!" << endl;
system("pause");
return 0;
}
1.2、注释
单行注释: //
多行注释:/* */
1.3、变量
创建变量:数据类型 + 变量名 = 变量值;
如 int a = 10;
1.4、常量
作用:用于记录程序中不可更改的数据
C++定义常量的两种方式:
a)#define Day 7
b)const int day = 7;
1.5、数据类型
a)整型:short(2 Byte);int(4 Byte);long(4 Byte,linux64位系统 8 Byte);longlong(8 Byte);
b)实型:float (4 Byte);double (8 Byte);
c)字符型:char(1 Byte)字符型是将字符对应的ASCII码存在存储单元中;
d)转义字符:(1 Byte)
e)字符串型:
string str1 = "hello,world~";要添加头文件 #include<string>
char str2[ ] = "hello,world~";
f)布尔类型:(1 Byte)bool flag = true;#只要是非0的值都代表true,0代表false;
1.6、数据输入(cin)与数据输出(cout)
int a = 0;
cin >> a;
cout << a << endl;
二、选择结构(较简单就略过了条件判断结构)
2.1、三目运算符(返回的是变量,可以继续赋值)
语法:表达式1 ? 表达式2 : 表达式3
若表达式1返回true,则执行表达式2,否则执行表达式3。
#include <iostream>
using namespace std;
int main() {
int a = 10;
int b = 5;
int max = a > b ? a : b;
cout << max << endl;
system("pause");
return 0;
}
2.2、switch 语句(执行多条件分支语句)
a)switch 语句中表达式类型只能是整型或者字符型;
b)case里如果没有break,那么程序会一直向下执行;
int score = 0;
switch(score){
case 10:
cout << "perfect~" << endl;
break;
case 9:
cout << "good" << endl;
break;
default:
cout << "just so so" << endl;
break;
}
三、循环结构
3.1、while 循环结构
语法:while(循环条件){ 循环语句 }
#include <iostream>
using namespace std;
int main() {
int num = rand() % 100 + 1;
cout << num << endl;
int yournum = 0;
while (yournum != num) {
cout << "再猜一下" << endl;
cin >> yournum;
}
system("pause");
return 0;
}
3.2、do while 循环结构
语法:do{ 循环语句 } while(循环条件)
3.3、for 循环结构
语法:for(初始变量;循环条件;变量变化){ 循环语句 }
四、跳转语句
4.1、break 语句
作用:用于跳出选择结构 或 循环结构;
4.2、continue 语句
作用:在循环语句中,跳出本次循环中未执行的语句,继续执行下一次循环;
4.3、goto语句
作用:无条件跳转语句
语法:goto 标记;