C++无符号短裤的划分导致 int
C++ division of unsigned shorts results in int
为什么C++中两个int
unsigned short
的划分结果?我创建了一个可以轻松测试的示例,例如 http://cpp.sh/
// Example program
#include <iostream>
#include <string>
#include <typeinfo>
int main(){
unsigned short a = 1;
unsigned short b = 1;
auto c = a/b;
std::cout<<"result of dividing unsigned shorts is: "<<typeid(c).name()<<std::endl;
}
来自隐式转换/数字提升/积分提升:
小整型(如 CHAR(的 pr值可以转换为较大整型(如 int(的 pr值。特别是,算术运算符不接受小于 int 的类型作为参数,并且在左值到右值转换后自动应用积分提升(如果适用(。
[编辑] 从同一页面:
无符号字符、char8_t(自 C++20 以来(或 无符号 short 如果可以保存其整个值范围,则可以转换为 int, 否则将无符号 int
转换为
OP 的案例属于(突出显示的(案例,因为sizeof int = 4 > 2 = sizeof unsigned int
在目标平台上(根据发布的链接(。如果不是这种情况(即int
不能容纳整个unsigned int
值范围,例如在sizeof int == sizeof short
的平台上(,那么两个操作数都会被积分提升规则提升为unsigned int
,而除法的结果将是unsigned int
,而是
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- int(c) 和 c-'0' 之间的区别。C++
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 为什么野牛仍在使用"int yylex(void)",却找不到"int yylex(YYS
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 是否可以从int转换为enum类类型
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 'short int'持有的值溢出,但"自动"不会溢出?
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 调用'begin(int [n])'没有匹配函数
- 没有显式声明的int[]中的foreach
- 在c++中访问int到类对象的映射时出错
- 为什么我无法更改"set<set>"循环中的值<int>
- C++无符号短裤的划分导致 int
- 用getline在字符串中从文件中读取,然后将数字从int数组中的字符串划分
- 拔河:将一组n个对象int划分为多个子集
- C++漂浮和 int 划分奇怪的行为
- 将 Object int 数据成员转换为浮点数并划分会将奇怪的数据 cout 附加到控制台