[英]C++ create an integer variable with the largest integer value supported
我得到了一项任务,在问题中有这样一行:
- min:一个 int,用于跟踪到目前为止看到的数字的最小值。 最初 min 应该是支持的最大 integer 值(不要对该值进行硬编码)。
我确保在int minimum;
之前写unsigned
; 所以这是积极的。 当我打印未初始化的minimum
变量的值时,我得到3435973836
。 那是“支持的最大 integer 值”吗? 我的导师给出的 output 显示它是2147483647
。 我是否应该做任何额外的事情,或者这个值在每台计算机上都是随机的?
可以存储在 integer 中的最大值取决于类型以及您的系统,因此它可能与您的教师系统上的最大可能值不同。
在您的系统上获取数字类型的最大可能值的正确方法是使用std::numeric_limits
。 例如:
#include <iostream>
#include <limits>
int main() {
std::cout << "The largest value an unsigned int can hold is "
<< std::numeric_limits<unsigned int>::max()
<< " and the smallest value is "
<< std::numeric_limits<unsigned int>::min()
<< std::endl;
return 0;
}
Output:
unsigned int 可以容纳的最大值是 4294967295,最小值是 0
请注意,从未初始化的变量中读取是未定义的行为,这总是错误的,永远不应依赖。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.