为什么这里需要显式类型转换

Why explicit typecasting is required here?

本文关键字:类型转换 这里 为什么      更新时间:2023-10-16

为什么我们明确需要将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为什么会这样?

因为nint类型,所以n * n也是int类型。C++没有"动态加宽"。

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

最后,请注意,即使100000对于int来说也可能太大 - std::numeric_limits<int>::max()可以小到 32767。如果您希望代码可移植,则需要编写long n = 100000;和给定的t表达式。