有符号字符的乘法问题 [英] Problem with multiplication of signed chars

查看:175
本文介绍了有符号字符的乘法问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

讨论这个的答案我发现,下面的代码打印 -1 1 。为什么?在我看来,它应该在乘法期间打印两个 1 的溢出溢出。

  signed char c1 = numeric_limits< signed char> :: min(); 
signed char c2 = -1;
cout< c1 * c2 / c1 < endl;
signed char result = c1 * c2;
cout< result / c1<< endl;


解决方案

c1 可能具有像 -128 的值,例如。在乘法中,整数促销将导致 c1 c2 转换为 int

c1

int 与值 128 因此 c1 * c2 / c1 将成为 int ,值为 -1



-1 对于第一个输出看起来正确。



对于第二个版本, c1 * c2 的结果将不适合 signed char ,并且将转换为实现定义的结果, -128 而不是 128


Discussing this answer I find out that the code bellow prints -1 and 1 in visual studio. Why? In my opinion it should print two 1s despit overflow during multiplication.

signed char c1 = numeric_limits<signed char>::min();
signed char c2 = -1;
cout << c1 * c2 / c1 << endl;
signed char result = c1 * c2;
cout << result / c1 << endl;

解决方案

c1 might have a value like -128, say. In the multiplication, integer promotions will cause both c1 and c2 to be converted to type int before the operation is performed.

c1 * c2 is then going to be a int with value 128 so c1 * c2 / c1 is going to be an int with value -1.

-1 for the first output looks correct to me.

For the second version, typically the assignment of the result of c1 * c2 won't fit into a signed char and will convert to an implementation-defined result, perhaps -128 instead of 128.

这篇关于有符号字符的乘法问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆