java - 对我的 int 和 long 代码差异的问题
问题描述
嘿嘿,当我学习新的基础知识时,我发现 int 的限制为 2^32 -1 所以我想知道我是否可以用 unsigned int 或 long 来增加它
我尝试了以下
class test {
public static void main(String[] args) {
int i;
int a=0;
for (i=1; i>0; i++) {
a++;
}
System.out.println("Done, a=" +a);
}
}
我注意到改变 long a=0 不会改变输出,但为什么呢?
将 i 更改为 long 确实会更改输出
在我的理解中 i 的值仍然为 0 那么它为什么会达到极限呢?
有没有办法改进我找到极限的方法?
解决方案
如果a
是我们的 long,我们的程序将在达到 a 的 MAXVALUE 之前停止 for 循环long
。所以 的值为a
2147483647。
class Test {
public static void main(String[] args) {
int i;
long a = 0;
for(i = 1; i > 0; i++) {
// This will stop incrementing when we reach the MAXVALUE
// of an int (i), which is 2147483647
}
System.out.println(a);
}
}
如果是我们的 long,我们的程序将在达到(整数)的 MAXVALUE后i
尝试循环(递增) -所以我们的程序将挂起并且不会打印任何内容。a
class Test {
public static void main(String[] args) {
long i;
int a = 0;
for(i = 1; i > 0; i++) {
// This will try to increment **a** beyond the max
// value of an int
}
System.out.println(a);
}
}
推荐阅读
- ios - 在 Swift 中启动并将字符串传递给目标视图控制器
- python - 从姓名列表中生成学生对,每周生成新对
- php - 用于配方数据库的 PHP 和 MySQL
- angular - 更新到 Angular 7 - @angular/animation 出错
- installation - Netlogo:如何删除“go”结果保留“setup”结果?
- metal - 'nextDrawable' 非常难以捉摸的金属问题
- google-app-engine - 将 Google Cloud Memorystore 与 App Engine 服务连接起来
- wordpress - 从 wordpress 页面模板中的列表中删除喜欢不起作用
- python - Python - 基于另一个数组中相应最大值的非唯一值数组
- python - 棉花糖领域依赖