INSERT INTO dbo.UdtEquipmentsStaging
( [Type], [ModelID], [AccessoryID], [Make], [Model], [Category], [CategoryDescription], [Grouping], [Item], [RequiredModel], [SKU], [ProductNum]
, [Speed], [Description], [Cost], [Cost2], [Cost3], [Cost4], [Cost5], [Outcost], [MSRP], [Discontinued], [PercentMSRP], [ServiceType], [ServiceTypeColor]
, [ConnectivityFee], [ConnectFee], [InstallFee], [Notes], [ManufactureNotes]
, [Special1], [Special2], [Special3], [Special4], [Special5], [Special6], [Special7], [Special8], [Special9], [Special10], [Special11], [Special12], [Special13]
, [Special14], [Special15], [Special16], [Special17], [Special18], [Special19], [Special20], [Special21], [Special22], [Special23], [Special24], [Special25]
, [Special26], [Special27], [Special28], [Special29], [Special30], [Special31], [Special32], [Special33], [Special34], [Special35], [Special36], [Special37]
, [Special38], [Special39], [Special40])
SELECT [Type], [ModelID], [AccessoryID], [Make], [Model], [Category], [CategoryDescription], [Grouping], [Item], [RequiredModel], [SKU], [ProductNum]
, [Speed], [Description], [Cost], [Cost2], [Cost3], [Cost4], [Cost5], CONVERT(NUMERIC(18,2), CAST([Outcost] AS FLOAT)), [MSRP], [Discontinued], [PercentMSRP], [ServiceType], [ServiceTypeColor]
, [ConnectivityFee], [ConnectFee], [InstallFee], [Notes], [ManufactureNotes]
, [Special1], [Special2], [Special3], [Special4], [Special5], [Special6], [Special7], [Special8], [Special9], [Special10], [Special11], [Special12], [Special13]
, [Special14], [Special15], [Special16], [Special17], [Special18], [Special19], [Special20], [Special21], [Special22], [Special23], [Special24], [Special25]
, [Special26], [Special27], [Special28], [Special29], [Special30], [Special31], [Special32], [Special33], [Special34], [Special35], [Special36], [Special37]
, [Special38], [Special39], [Special40]
FROM @Equipments
该程序的输出为-128。据我所知,字符变量将溢出,所有位将为0.并且取两个补码将再次为0.可以有人解释这个过程吗?
编辑:只是为了澄清这不是我的计划。这是竞争性考试中的编程问题。
答案 0 :(得分:5)
关于溢出的假设是不正确的。溢出无符号类型会将所有位设置为零,但溢出签名类型未定义,因此可能会产生任何值。
因此,您得到的结果取决于您的(编译器)实现。可以解释一下
char
。char
有8位。鉴于所有这些假设(并记住,这些假设中无由C指定),将127
增加为最大可能char
值(表示为0111 1111
})产生-128
,最小可能值(表示为1000 0000
)。
TL; DR - 您的代码未定义,请勿编写此类代码。
答案 1 :(得分:0)
由于你的char是SIGNED,它可以介于-128和127之间(以8位为单位),因为你正在递增直到它达到最大值然后溢出并变成 - 值,因为那是多么负面值以位写入。 看看下面的图片:
P.S。在循环中进行一些打印,你也可以自己解决。
答案 2 :(得分:0)
实际上,在每次迭代时,循环将i
增加1
,这会导致i = 127
。
0111-1111
。1
递增,那么0111-1111
+ 0000-0001
= 1000-0000
1000-0000
= -127
希望你能得到它。