本文介绍了整数求和蓝调,短 += 短问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C# 程序:

short a, b;
a = 10;
b = 10;
a = a + b; // Error : Cannot implicitly convert type 'int' to 'short'.

// we can also write this code by using Arithmetic Assignment Operator as given below

a += b; // But this is running successfully, why?

Console.Write(a);

推荐答案

这里有两个问题.第一个是为什么短加短的结果是int?"

There are two questions here. The first is "why is short plus short result in int?"

好吧,假设空头加空头是空头,看看会发生什么:

Well, suppose short plus short was short and see what happens:

short[] prices = { 10000, 15000, 11000 };
short average = (prices[0] + prices[1] + prices[2]) / 3;

如果这个计算是在短裤中完成的,那么平均值当然是 -9845.总和大于可能的最大短路数,因此它环绕为负数,然后除以负数.

And the average is, of course, -9845 if this calculation is done in shorts. The sum is larger than the largest possible short, so it wraps around to negative, and then you divide the negative number.

在一个整数算术环绕的世界中,在 int 中进行所有计算更为明智,int 类型可能具有足够的范围,典型计算不会溢出.

In a world where integer arithmetic wraps around it is much more sensible to do all the calculations in int, a type which is likely to have enough range for typical calculations to not overflow.

第二个问题是:

  • short 加 short 是 int
  • 将 int 赋值给 short 是非法的
  • a +=b 与 a = a + b 相同
  • 因此 short += short 应该是非法的
  • 为什么这是合法的?

问题的前提不正确;上面的第三行是错误的.C# 规范在第 7.17.2 节中说明

The question has an incorrect premise; the third line above is wrong. The C# specification states in section 7.17.2

否则,如果选定的运算符是一个预定义的运算符,如果返回所选运算符的类型是显式转换为x,如果 y 是隐式可转换的到 x 的类型或运算符是 a移位运算符,则操作为计算为 x = (T)(x op y),其中 T是 x 的类型,除了 x 是仅评估一次.

编译器代表您插入演员表.正确的推理是:

The compiler inserts the cast on your behalf. The correct reasoning is:

  • short 加 short 是 int
  • 将 int 赋值给 short 是非法的
  • s1 += s2 与 s1 = (short)(s1 + s2) 相同
  • 因此这应该是合法的

如果它没有为您插入强制转换,那么就不可能在许多类型上使用复合赋值.

If it did not insert the cast for you then it would be impossible to use compound assignment on many types.

这篇关于整数求和蓝调,短 += 短问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 14:30