📚 什么是变量?
变量的定义
变量是程序中用于存储数据的容器。就像一个有名字的盒子,可以存放各种类型的值。
- ✅ 变量有名称(标识符)
- ✅ 变量有类型(决定能存什么数据)
- ✅ 变量有值(存储的具体数据)
- ✅ 变量的值可以改变
声明和初始化变量
#include <iostream>
using namespace std;
int main() {
int age;
int score = 100;
int height;
height = 175;
int x = 1, y = 2, z = 3;
return 0;
}
💡 命名规则:
• 只能包含字母、数字、下划线
• 不能以数字开头
• 区分大小写(age和Age是不同的变量)
• 不能使用关键字(如int、return等)
🛠️ 变量常用方法
变量的输入和输出
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
int age;
cout << "请输入姓名:";
cin >> name;
cout << "请输入年龄:";
cin >> age;
cout << "姓名:" << name << endl;
cout << "年龄:" << age << endl;
return 0;
}
💡 关键知识点:
• cin - 标准输入流(console input)
• >> - 输入运算符
• cout - 标准输出流
• << - 输出运算符
🔄 变量交换演示
观察如何交换两个变量的值
选择一种交换方法查看代码...
🚀 变量高级特性
常量(const)
常量是值不能被改变的变量,使用 const 关键字声明。
#include <iostream>
using namespace std;
int main() {
const double PI = 3.14159;
const int MAX_SIZE = 100;
cout << PI << endl;
return 0;
}
变量作用域
变量的作用域决定了变量在程序中的可见范围。
#include <iostream>
using namespace std;
int globalVar = 100;
int main() {
int localVar = 50;
cout << globalVar << endl;
cout << localVar << endl;
return 0;
}
类型转换
#include <iostream>
using namespace std;
int main() {
int a = 10;
double b = a;
double x = 3.14;
int y = (int)x;
int z = static_cast<int>(x);
cout << "b = " << b << endl;
cout << "y = " << y << endl;
cout << "z = " << z << endl;
return 0;
}
📝 实战练习
📝 小练习:变量声明
以下哪些变量声明是正确的?
int 1stNumber = 10;
int my_age = 18;
double price$ = 99.9;
string name = "Tom";
选择答案查看解析...