简体   繁体   中英

division of short returns int c# (short/short=int ?!)

I'm trying the following:

short value1 = 4;
short value2 = 2;
short result = value1 / value2;

Cannot implicitly convert type 'int' to 'short'. An explicit conversion exists (are you missing a cast?)

Is there no such thing as division for short?
Is there a reason why short/short returns an int or just because?
The reason I'm wondering, is because I can divide int's eventhough its limitations (cast back from float)

You are absolutely right:

When you divide two int numbers (between -2147483648 and 2147483647), the result will mostly be between the same boundaries, so the division result should be int , which is correct.

When you divide two short numbers (between -32768 and 32767), the result will mostly be between the same boundaries, so the division result should be short , while it is int , so this is wrong.

Also the documentation is wrong: it mentions the integer division being an integer type, while it clearly is not just an integer type, but the integer type.

By the way: there is one ±fault in my explanation (hence the "mostly"):

(-32768) / (-1) is not within the short boundaries, but what the heck:
(-2147483648) / (-1) is also not within the int boundaries!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM