为什么这里需要显式类型转换
Why explicit typecasting is required here?
为什么我们明确需要将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)n
给10000000000
其中作为 t=n*n
给1410065408
为什么会这样?
因为n
是int
类型,所以n * n
也是int
类型。C++没有"动态加宽"。
写入1LL * n * n
强制将n
类型隐式转换为long long
类型。
最后,请注意,即使100000
对于int
来说也可能太大 - std::numeric_limits<int>::max()
可以小到 32767。如果您希望代码可移植,则需要编写long n = 100000;
和给定的t
表达式。
相关文章:
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- C++中的双指针类型转换
- 逐位操作的隐式类型转换
- 模板中的类型转换
- 在 C++(和 C)中进行类型转换时明显不一致
- 字符类型转换不兼容
- 将复杂的非基元C++数据类型转换为 Erlang/Elixir 格式,以使用 NIF 导出方法
- C++:用户定义的显式类型转换函数错误
- 将类指针类型转换为键时出错
- 通过引用传递参数时C++类型转换
- 在 C++ 中将一个模板类型的对象类型转换为另一个模板类型
- C++显式类型转换(C 样式强制转换)的强制表示法和static_cast的多种解释
- C++无效的函数类型转换
- 在将派生类指针类型转换为派生类指针后,从基类指针调用派生类函数
- 如何将Windows产品类型转换为名称?
- 通过构造函数方法输出的类到类类型转换是 5500 为什么不是 5555
- 事件系统:使用类型转换或联合进行继承
- 如何在参数中定义隐式类型转换的构造函数?
- 为什么这里需要显式类型转换