用c++编写一个程序来输出不同数据类型(short, int, long, float, double, char)所占的存储空间大小。
时间: 2024-12-16 15:14:38 浏览: 11
在C++中,可以使用`sizeof`运算符来获取数据类型的存储空间大小。下面是一个简单的程序,它会打印出不同类型变量占用的空间:
```cpp
#include <iostream>
using namespace std;
int main() {
cout << "Size of short: " << sizeof(short) << " bytes" << endl;
cout << "Size of int: " << sizeof(int) << " bytes" << endl;
cout << "Size of long: " << sizeof(long) << " bytes" << endl;
cout << "Size of float: " << sizeof(float) << " bytes" << endl;
cout << "Size of double: " << sizeof(double) << " bytes" << endl;
cout << "Size of char: " << sizeof(char) << " bytes" << endl;
return 0;
}
```
运行这个程序,你会看到输出类似于:
```
Size of short: 2 bytes
Size of int: 4 bytes
Size of long: 8 bytes (这取决于平台,通常是4字节,但在64位系统上可能是8字节)
Size of float: 4 bytes
Size of double: 8 bytes
Size of char: 1 byte
```
阅读全文