考纲
一、计算机基础知识
二、变量
1.变量的声明
- 想要使用变量,必须先做“声明”,也就是告诉计算机要用到的数据叫什么名字。变量声明的标准语法可以写成:
数据类型 变量名;
#include <iostream>
using namespace std;
int main()
{
int a; //声明一个变量a
cin>>a; //把输入的值给a变量
cout<<"a="<<a;
}
结果:
2.变量的声明且赋值
#include <iostream>
using namespace std;
int main()
{
int a = 1; //声明变量a,并赋值为1
cout<<a; //结果:输出1
}
- 全局变量和局部变量
#include <iostream>
using namespace std;
// 全局变量
int number = 100;
int main()
{
// 局部变量
int number = 1;
// 访问局部变量
cout << "number = " << number << endl;
// 访问全局变量,number前面要加上双冒号::
cout << "number = " << ::number << endl;
}
3.变量名的规则
- 【规则1】:变量名包含字母、数字、下划线,但数字不能在变量名首位,例如以下变量名:
a(合法)、a123(合法)、_xyz(合法)、2b(不合法,不能以数字开头)
- 【规则2】:具有特殊含义的单词不能作为变量名,否则会报错,因为它们在C++中已经代表了特定的意思,例如以下单词:
while, int, if, char, long, bool 等等。
三、输入输出
- cout:输出
#include <iostream>
using namespace std;
int main()
{
cout<<"Hello World"<<endl; //endl:表示换行
cout<<"Hello C++"<<endl;
}
结果:
- cin:输入
#include <iostream>
using namespace std;
int main()
{
int a; //声明一个变量a
cin>>a; //把输入的值给a变量
cout<<"a="<<a;
}
假如键盘输入6,结果:
- 连续输入输出
#include <iostream>
using namespace std;
int main()
{
int a; //声明变量a
int b; //声明变量b
cin>>a>>b; //输入a和b
cout<<a<<" "<<b; //输出a和b
}
假如键盘输入2,回车再输入8,结果: