为什么向 long 变量添加值会使其降低?

发布于 2025-01-12 21:23:46 字数 380 浏览 2 评论 0原文

我试图将 30 天添加到 System.long a = System.currentTimeMillis() + ((long)30 * 24 * 60 * 60 * 1000); 但它正在减少该值?为什么?这是我尝试过的

int days = 30;
long a = System.currentTimeMillis();
long b = a + (days * 24 * 60 * 60 * 1000);

根据我运行代码的时间,结果是:

a = 1646737213282 , b = 1645034245986

为什么b <一个?

I am trying to add 30 days to System.long a = System.currentTimeMillis() + ((long)30 * 24 * 60 * 60 * 1000); but it is deceasing the value? Why? This is what i have tried

int days = 30;
long a = System.currentTimeMillis();
long b = a + (days * 24 * 60 * 60 * 1000);

According to the time I run the code, it was the result:

a = 1646737213282 , b = 1645034245986

Why b < a ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

苹果你个爱泡泡 2025-01-19 21:23:46

问题是超出了 int 范围。最大 int 范围为

-2,147,483,648 (-231) 到 2,147,483,647 (231-1)

当您相乘时,它存储为 int。但是,这不是限制。因此,解决方案是将其解析为 long。你可以看看我下面的代码:

int days = 30;
long a = System.currentTimeMillis();
long b = a + ((long)days * 24 * 60 * 60 * 1000);
System.out.println("a = " + a + "       b = " + b);

但是如果你想优化代码,这个代码会更好:

long a = System.currentTimeMillis() + ((long)30 * 24 * 60 * 60 * 1000);
System.out.println("a = " + a);

它节省了你的两行代码

The issue is that the int range is being exceeded. The max int range is from

-2,147,483,648 (-231) to 2,147,483,647 (231-1)

When you multiply, it is stored as a int. But, that's not the limit. So, the solution will be to parse it to a long. You can check out my code below:

int days = 30;
long a = System.currentTimeMillis();
long b = a + ((long)days * 24 * 60 * 60 * 1000);
System.out.println("a = " + a + "       b = " + b);

But if you want to optimise the code, this code will be better:

long a = System.currentTimeMillis() + ((long)30 * 24 * 60 * 60 * 1000);
System.out.println("a = " + a);

It saves your 2 lines of code ????

But, I'd also prefer you to use a method

long addDays(int days){
    return System.currentTimeMillis() + ((long)days * 24 * 60 * 60 * 1000);
}

and then

int a = addDays(30);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文