整数总结蓝调,短+短=问题 [英] Integer summing blues, short += short problem

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

问题描述

计划在C#中:

 短期A,B;
一个= 10;
B = 10;
一个= A + B; //错误:无法隐式转换类型'诠释'到'短'。//我们也可以使用算术赋值运算符下面给出写这篇codeA + = B; //但这运行成功,为什么?Console.Write(一);


解决方案

这里有两个问题。首先是为什么是短加上短期结果INT?

好吧,假设短期加短很短,看看会发生什么:

 短[] =价格10000 {,15000,11000};
短期平均=(价格[0] +价格[1] +价格[2])/ 3;

和的平均值是,当然,-9845如果此计算是在短裤完成。之和小于最大可能短大,因此它绕到负,然后除以负数

在整数运算环绕它是更明智的做INT所有计算的世界里,一个类型,是可能有足够的范围,典型的计算,不会溢出。

第二个问题是:


  • 短加上短期为int

  • 要短分配int是非法的

  • 一个+ = b是一样的= A + B

  • 因此短+短=应该是非法

  • 那么,为什么是这样合法吗?

问题有一个不正确premise;上面第三行是错误的。在第7.17.2中的C#规范规定


  

否则,如果所选择的操作者是
  一个predefined操作员,如果返回
  选定的运算符的类型
  明确地转换为的类型
  X,如果y是隐式转换
  到x的类型或操作员是一个
  移位运算符,则操作是
  评价为x =(T)(X运算y)的,其中T
  是x的类型,不同的是,x是
  只计算一次。


编译器插入代表你投。正确的推理是:


  • 短加上短期为int

  • 要短分配int是非法的

  • S1 + = s2的是相同的S1 =(短)(S1 + S2)

  • 因此这应该是合法

如果它没有插入投给你那么这将是不可能的多种类型使用复合赋值。

Program in 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);

解决方案

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;

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.

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.

The second question is:

  • short plus short is int
  • assigning int to short is illegal
  • a +=b is the same as a = a + b
  • therefore short += short should be illegal
  • so why is this legal?

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

Otherwise, if the selected operator is a predefined operator, if the return type of the selected operator is explicitly convertible to the type of x, and if y is implicitly convertible to the type of x or the operator is a shift operator, then the operation is evaluated as x = (T)(x op y), where T is the type of x, except that x is evaluated only once.

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

  • short plus short is int
  • assigning int to short is illegal
  • s1 += s2 is the same as s1 = (short)(s1 + s2)
  • therefore this should be legal

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

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

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