【问题标题】:Why explicit typecasting is required here?为什么这里需要显式类型转换?
【发布时间】:2019-06-21 06:46:15
【问题描述】:

为什么我们在乘法中明确需要将int 类型转换为long long

t=(long long)n*(long long)n 给出正确答案,但是 t=n*n 给出错误答案:

#include <iostream>
using namespace std;

int main() {
int n=100000;
long long int t;
t=(long long)n*(long long)n;
//t=n*n  (This gives wrong answer)
printf("%lld",t);
return 0;
}

t=(long long)n*(long long)n10000000000 然而 t=n*n1410065408 为什么会这样?

【问题讨论】:

  • n 是一个int,所以n*n 也是一个int,而10000000000 在大多数机器上不适合int。如果您将int n = 100000; 更改为long long n = 100000;,那么这也可以解决问题。

标签: c++ typecasting-operator


【解决方案1】:

因为nint 类型,所以n * n 也是int 类型。 C++ 中没有“动态扩展”。

编写 1LL * n * n 会强制将 ns 隐式转换为 long long 类型。

最后,请注意,即使100000 可能太大,int - std::numeric_limits&lt;int&gt;::max() 也可以小至 32767。如果您希望您的代码可移植 你需要写成long n = 100000;t 的表达式。

【讨论】:

    猜你喜欢
    • 2011-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-16
    相关资源
    最近更新 更多