为什么"int"是无法与"j"一起正常工作但是好久好吗? [英] Why is "int" not working correctly with "j" but long long is working fine?

查看:150
本文介绍了为什么"int"是无法与"j"一起正常工作但是好久好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的int j代码:

void solve(){
    unsigned long long n;
    cin>>n;
    unsigned long long sum = 0;
    int j = 1;
    for(int i=3;i<n+1;i+=2){
        sum += ((4*i)-4)*(j);
        j++;
    }
    cout<<sum<<"\n";
    }

Input:
499993

Output:
6229295798864

但是它给出了错误的输出,这是我的long long j代码,可以正常工作:

but it is giving wrong output, and here is my code with long long j which is working fine:

void solve(){
    int n;
    cin>>n;
    unsigned long long sum = 0;
    long long j = 1;
    for(int i=3;i<n+1;i+=2){
        sum += ((4*i)-4)*(j);
        j++;
    }
    cout<<sum<<"\n";
    }

Input:
499993

Output:
41664916690999888

在这种情况下,j的值远低于499993,该值在int范围内,但仍然无法正常工作.为什么实际上会发生这种情况?

In this case value of j is well below 499993, which is in int range but still, it's not working. Why is it actually happening?

此处是实际问题的链接.万一你想看看.

Here is the link to the actual problem. In case, you want to have a look.

推荐答案

请注意,由于ij均为int类型,因此((4*i)-4)*(j)的结果为int.仅当将((4*i)-4)*(j)添加到sum时,右侧才会提升为unsigned long long.但是表达式((4*i)-4)*(j)在提升之前已经溢出了int类型的大小达足够大的n.

Notice that the result of ((4*i)-4)*(j) is an int, since both i and j are int types. The right hand side is promoted to unsigned long long only when adding ((4*i)-4)*(j) to sum. But the expression ((4*i)-4)*(j) already overflows the size of the int type for a large enough n before being promoted.

但是,如果将ij中的任何一个更改为unsigned long long,则表达式((4*i)-4)*(j)会被计算为unsigned long long,并且安全地在大小限制内.

However, if you change either of i or j to unsigned long long, the expression ((4*i)-4)*(j) is evaluated to unsigned long long, safely inside the size limits.

这篇关于为什么"int"是无法与"j"一起正常工作但是好久好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆