目录
1、//输出"Hello World"
#include <iostream>
using namespace std;
int main1()
{
cout << "Hello World!" << endl;
system("pause");
return 0;
}
2、//定义变量
int main2()
{
int a = 10;
cout << "a = " << a << endl;
system("pause");
return 0;
}
3、//定义常量
#define Day 7//宏常量
int main3()
{
const int Month = 30;//const修是变量==定义常量
cout << "一周有" << Day << "天" << endl;
cout << "一个月有" << Month << "天" << endl;
system("pause");
return 0;
}
4、//标识符命名规则
/*
·标识符不能是关键字
·标识符只能由字母、数字、下划线组成
·第一个字符必须为字母或下划线
·标识符中字母区分大小写I
*/
5、//sizeof关键字
int main4()
{
int aaa = 10;
cout << "int占用内存空间是:" << sizeof(int) << endl;
cout << "aaa占用的内存空间是:" << sizeof(aaa) << endl;
cout << "long long(长长整型)占用的内存空间是:" << sizeof(long long) << endl;
system("pause");
return 0;
}
6、//数据类型
6.1 //浮点型变量
int main5()
{
float a = 3.14f;//注意加 f
double b = 3.1415;
float c = 3e2;//科学计数法3*10^2,不加 f
cout << "float a = " << a << endl;
cout << "double b =" << b << endl;
cout << "科学技术法不加 f, 3e2 = " << c << endl;
system("pause");
return 0;
}
6.2 //字符型
/*
C和C++中字符型变量只占用1个字节。
字符型变量并不是把字符本身放到内存中存储,而是将对应的 ASCII编码 放入到存储单元
*/
#include <string>//C++风格字符串,需要包含的头文件
int main6()
{
char ch = 'a';
//char ch2 = "a";//要用单引号
//char ch2 = 'abc';//只能有一个字符
cout << ch << endl;
cout << "char占用内存空间是:" << sizeof(char) << endl;
cout <<"对应的ASCII码是:"<< (int)ch << endl;
system("pause");
return 0;
}
6.3 //转义字符
/*
\n 换行
\t 水平制表(跳转到一下一个tab位置)
\\ 表示一个\
*/
6.4 //字符串型
int main7()
{
//C语言风格
char str1[] = "Hello World\n";
cout << str1<<endl;
//C++风格
string str2 = "World Hello\t";
cout << str2 ;
//system("pause"); //可以不写,非必须
return 0;
}
6.5 //布尔型bool
/*
true 非0值全为true
false 0
*/
int main8()
{
bool flag = true;
cout << flag<<endl;
//system("pause");
return 0;
}
7、//算术运算符 递增递减、前置后置
int main10()
{
//前置递增
int a = 10;
++a;//等价a=a+1
cout << a << endl;
//后置递增
int b = 10;
b++;
cout << b << endl;
//区别
//前置递增,先对变量进行++,再计算表达式
int x1 = 10;
int y1 = ++x1 * 10;
cout << y1 << endl;
//后置递增,先计算表达式,再对变量进行++
int x2 = 10;
int y2 = x2++ * 10;
cout << y2 << endl;
system("pause");
return 0;
}
8、//三目运算符
/*
语法:表达式1 ? 表达式2∶表达式3
如果表达式1的值为真,执行表达式2,并返回表达式2的结果;
如果表达式1的值为假,执行表达式3,并返回表达式3的结果。
*/
int main11()
{
int a = 10;
int b = 20;
int c;
c = a > b ? a : b;
cout << "c = " << c << endl;
//C++中,若三目运算符返回的是变量,可以继续赋值
(a > b ? a:b) = 30;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
system("pause");
return 0;
}
9、//switch语句
int main12()
{
/*
电影评分
5 经典
4 好
3 一般
2及以下 烂片
*/
int score;
cout << "请给电影打分:" ;
cin >> score;
switch (score)//只能是整型或字符型
{
case 5:
cout << "经典" << endl;
break;//不能丢!!
case 4:
cout << "好" << endl;
break;
case 3:
cout << "一般" << endl;
break;
default:
cout << "烂片" << endl;
break;
}
system("pause");
return 0;
}
(哔哩哔 哩黑马程序员 C++教程 学习笔记,如有侵权请联系删除)