无输入题:用 sizeof(int) 与 sizeof(short) 问编译器当前平台的类型宽度,按序输出 4 2。
OJ: roj
题目 ID: 1016
难度:入门
标签:入门语法python
创建: 2026-09-29 13:31
更新: 2026-10-04 22:38
题目描述
分别定义 int、short 类型的变量各一个,依次输出它们的存储空间大小(单位:字节),两个整数之间用一个空格隔开。本题无输入,在本评测平台(64 位 g++)上输出 4 2。
思路
类型宽度由平台决定,不手写常数,直接用 sizeof(int) 和 sizeof(short) 问编译器即可。在常见 64 位平台上结果为 4 和 2,按题面顺序用空格分隔输出。
参考代码
Python 版:
python
#!/usr/bin/env python3
# Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
# rbook: -> https://rbook.roj.ac.cn https://rbook2.roj.ac.cn
# rainboy的学习导航网站: https://idx.roj.ac.cn
# create_at: 2026-09-29 13:32
# update_at: 2026-09-29 13:32
import struct
# 题面问的是 C/C++ 里 int / short 各占多少字节,而 Python 的 int 是任意精度对象,
# 拿 sizeof 去量 Python 对象没有意义。struct 用的正是 C 的 ABI 格式字符:
# 'i' 对应 int、'h' 对应 short,calcsize 返回该类型在当前平台的字节数,
# 与 C++ 的 sizeof(int) / sizeof(short) 同义。
INT_SIZE = struct.calcsize("i") # int:常见 32 位平台为 4 字节
SHORT_SIZE = struct.calcsize("h") # short:C 标准只要求不超过 int,常见为 2 字节
def solve() -> None:
# 本题无输入:两个量各只出现一次,按题面顺序交给 print 的空格分隔输出。
print(INT_SIZE, SHORT_SIZE)
if __name__ == "__main__":
solve()C++ 版(同一算法):
cpp
/**
* Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
* rbook: -> https://rbook.roj.ac.cn https://rbook2.roj.ac.cn
* rainboy的学习导航网站: https://idx.roj.ac.cn
* create_at: 2026-10-04 22:38
* update_at: 2026-10-04 22:38
*/
#include <cstdio>
int main() {
// sizeof 直接问编译器当前平台上该类型占的字节数,无需手写常数
int int_size = sizeof(int); // int 的存储空间大小
int short_size = sizeof(short); // short 的存储空间大小
// 按题面顺序:先 int 后 short,用一个空格隔开
printf("%d %d\n", int_size, short_size);
return 0;
}