除以两个整数结果是整数 [英] dividing two interger result is integer

查看:84
本文介绍了除以两个整数结果是整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int a = 5;
int b = 2;
float c = a/b;
Console.WriteLine(c);



答案:2

为什么答案是2它需要是2.5因为答案被分配浮点变量。 (或隐式转换需要在这里完成)


Answer: 2
why answer is 2 it's need to be 2.5 cause answer is assigned to float variable. (or implicit casting need to be done here)

int a = 5;
int b = 2;
float c = (float) a/b;
Console.WriteLine(c);



答案2.5



为什么我需要演员?


Answer 2.5

why i need casting?

推荐答案

因为它是这样设计的; https://msdn.microsoft.com/en-us/library/aa691373 (v = vs.71).aspx [ ^ ]
Because it was designed that way; https://msdn.microsoft.com/en-us/library/aa691373(v=vs.71).aspx[^]


MSDN [ ^ ]:

当你分割两个整数时,结果总是一个整数。

When you divide two integers, the result is always an integer.



这是你的第一个样本...

在你的第二个样本中,你将被除数转为浮动,因此除法是浮点数...


That's for your first sample...
In your second sample you cast the dividend to float so the division is of float...


在几乎所有编程语言中都有一个兼容类型之间的隐含和自动转换。

通常使用的规则是将表达式的所有数据类型转换为它们的超类型。通常在C中,如果对其中一个整数进行操作,则所有整数都将以浮点数或双精度进行转换,但这不是你的情况,因为你要划分两个同类数据,两个整数。因此,代码执行整数除法,然后在分配中,它将找到一个浮点数,前一个结果转换为浮点数(提升)然后分配。

在第二个例子中你做了'cast'强制编译器将第一个整数转换为float。在这种情况下,除法是在两个非同类型之间,超类型是浮点数。然后编译器首先将除数转换为浮点数,然后执行浮点除法并分配结果。

此链接很好地描述了许多语言的整个过程。



关于你的第二个问题我不明白你的意思是为什么我需要在这片中铸造代码或为什么我需要语言中的这种功能。在第一种情况下,您需要强制转换它,因为表达式是一个赋给float的整数表达式,因此它必须计算为integere而不是转换为要赋值。铸造你告诉编译器这是一个混合浮点表达式,我希望它计算为浮点数。

对于第二种情况,答案隐含在第一种情况下。
In almost all programming languages there is an implied and automatic conversion between compatible types.
The rule that is normally used is to convert all data types of an expression to the 'supertype' of them. Normally in C all integers will be converted in floats or doubles if thhey are operated against one of them, but this is n ot your case because you are dividing two homogenous types data, two integers. So happen that the code performs an integer division, then in the assignement, where it will found a float, the former result is converted to float (promoted) then assigned.
In the second example you have made a 'cast' forcing the compiler to convert the first integer to float. In this case the division is between two unhomogenous types, which supertype is the float. The compiler then will first convert the divisor to float than perform a floating point division and assign result.
This link describes very well the whole process for many languages.

About your second question I have not understood if you mean "Why I need casting in this piece of code" or "why I need such a feature in the language". In the first case you need to cast it because your expression is an integer expression assigned to a float, so it must be calculated as integere than converted to be assigned. Casting you are telling to the compiler this is a mixed float expression and I want it calculated as float.
For the second case the answer is implicit in the first case.


这篇关于除以两个整数结果是整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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