变量类型整数 [英] Variables types Integer

查看:93
本文介绍了变量类型整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好.
您能告诉我为什么我们不能编写这段代码吗?

Hello everybody.
would you tee tell me please why we cant write this code:

string message="Enter Number 1: ";
string message2 = "Enter Number 2: ";
Int16 num1, num2, sum, product;
Console.Write(message);
num1 = Convert.ToInt16(Console.ReadLine());

Console.WriteLine("You entered : "+ num1);
Console.Write(message2);
num2 = Convert.ToInt16(Console.ReadLine());
Console.WriteLine("You entered : " + num2);
sum = num1 + num2;
product = num1 * num2;
Console.WriteLine("{0}{1}\n{2}{3}\n{4}{5}",
                  "sum = ", sum, "Product = ", product,
                  "Sum * Product = ",sum*product);
Console.ReadLine();



其实我的问题是:
当我们声明一个像"sum"这样的int16变量时,它不能存储两个int16变量的总和吗?
但是如果我们的变量声明为int,则它们没有问题.
而且我知道我们必须像这样使用它



actually my problem is :
when we declare an int16 variable like "sum" it can''t store summation of two int16 variables?
but if our variables declare as int, there is no problem with them.
and i know we must use it like this

sum = (Int16)(num1+num2);


但请完整解释一下.
谢谢所有朋友.


but explain me complete please.
thank you all friends.

推荐答案

如您所知:
As you already know:
sum = (Int16)(num1 + num2);
product = (Int16)(num1 * num2);


将工作. (除非结果大于Int16.MaxValue(32.768))

为所有数字类型( 8位和16位整数类型除外)定义了算术运算符(+,-,*,/,%). Int16是16位整数.因此,如果将两个Int16(或Int8等)相乘,则会使用32位算术运算符.这就是为什么结果是Int32的原因.
始终使用最大"数据类型的运算符.如果添加一个16Bit值和一个32bit值,它将返回一个32bit值.如果将32位值和64位值相乘,将返回64位值.

一些例子:


will work. (unless the result is greater than Int16.MaxValue (32.768))

The arithmetic operators (+, −, *, /, %) are defined for all numeric types except the 8- and 16-bit integral types. Int16 is a 16 bit integral. So if you multiply two Int16 (or Int8 etc) a 32bit arithmetic operator is used. And that is why the result is a Int32.

Operator for the "biggest" datatype is always used. If you add a 16Bit value and a 32bit value it will return a 32bit value. If you multiply a 32bit value and a 64bit value it will return a 64bit value.

some examples:

Int16 + Int32 = Int32
Int16 + Int64 = Int64
Int32 * Int32 = Int32
Int32 * Int64 = Int64




我认为这是运算符重载的问题,当运算符执行其工作时,它会返回一个inter值,因为Int16比Int32所需的内存空间少,因此无法直接进行强制转换,您可以使用一些自定义的 Implicit 明确投射
或使用
Hi,

I think this is a problem with Operator Overloading, when operator perform its job it return an inter value as Int16 is required less memory space then Int32 so it cant be cast directly you may use some custom Implicit or Explicit casting
or Use
Convert.ToInt16

进行转换.

不能直接投射,因此会引发错误.

但是,当您声明Int时,它将起作用.

to Convert it.

there for it cant be directly cast so its throwing an error.

But when you declare Int then its work.


这篇关于变量类型整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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