📚 什么是数据类型?
数据类型的定义
数据类型决定了变量可以存储什么样的数据,以及占用多少内存空间。就像不同大小的盒子,用来装不同类型的物品。
- ✅ 决定存储空间大小
- ✅ 决定可存储的数据范围
- ✅ 决定可进行的操作
- ✅ 影响程序的性能
C++ 基本数据类型
#include <iostream>
using namespace std;
int main() {
int age = 18;
double pi = 3.14159;
char grade = 'A';
bool isPass = true;
return 0;
}
⚙️ 数据类型基本操作
🎮 互动实验:sizeof运算符
选择数据类型,查看其占用的内存大小
选择类型后点击"查看大小"...
数据类型详解
| 类型 |
大小 |
范围 |
示例 |
int |
4字节 |
-2,147,483,648 ~ 2,147,483,647 |
int x = 100; |
short |
2字节 |
-32,768 ~ 32,767 |
short s = 1000; |
long |
4或8字节 |
更大的整数范围 |
long l = 100000; |
float |
4字节 |
6-7位有效数字 |
float f = 3.14f; |
double |
8字节 |
15-16位有效数字 |
double d = 3.14159; |
char |
1字节 |
-128 ~ 127 |
char c = 'A'; |
bool |
1字节 |
true 或 false |
bool b = true; |
🛠️ 数据类型常用方法
使用sizeof获取类型大小
#include <iostream>
using namespace std;
int main() {
cout << "int 大小:" << sizeof(int) << " 字节" << endl;
cout << "double 大小:" << sizeof(double) << " 字节" << endl;
cout << "char 大小:" << sizeof(char) << " 字节" << endl;
cout << "bool 大小:" << sizeof(bool) << " 字节" << endl;
cout << "float 大小:" << sizeof(float) << " 字节" << endl;
cout << "long 大小:" << sizeof(long) << " 字节" << endl;
return 0;
}
💡 关键知识点:
• sizeof 是运算符,不是函数
• 返回类型占用的字节数
• 可以在编译时确定
• 也可以用于变量:sizeof(x)
🔄 类型转换演示
观察不同类型之间的转换效果
输入数值后点击"执行转换"...
🚀 数据类型高级特性
隐式类型转换
编译器自动进行的类型转换,通常从低精度向高精度转换。
#include <iostream>
using namespace std;
int main() {
int a = 10;
double b = a;
char c = 'A';
int d = c;
int x = 5;
double y = 2.5;
double result = x + y;
cout << "b = " << b << endl;
cout << "d = " << d << endl;
cout << "result = " << result << endl;
return 0;
}
显式类型转换(强制转换)
程序员手动指定的类型转换,可能导致数据丢失。
#include <iostream>
using namespace std;
int main() {
double pi = 3.14159;
int whole = (int)pi;
double x = 9.99;
int y = static_cast<int>(x);
int big = 1000;
char small = (char)big;
cout << "whole = " << whole << endl;
cout << "y = " << y << endl;
cout << "small = " << (int)small << endl;
return 0;
}
⚠️ 注意事项:
• 高精度 → 低精度会丢失数据
• 优先使用 static_cast
• 转换前检查数据范围
• 避免不必要的类型转换
typedef 和 auto 关键字
#include <iostream>
using namespace std;
int main() {
typedef unsigned long ulong;
ulong bigNum = 100000;
auto x = 10;
auto y = 3.14;
auto z = "hello";
cout << "bigNum = " << bigNum << endl;
cout << "x = " << x << endl;
cout << "y = " << y << endl;
return 0;
}
📝 实战练习
📝 小练习:类型判断
以下变量声明中,哪个是正确的?
#include <iostream>
using namespace std;
int main() {
int a = 3.14;
double b = 100;
char c = "A";
bool d = 1;
return 0;
}
选择答案查看解析...