如果我有这样的事情:
int i = 123; float f = 123.1; if (f > i) {} else {}i将被提升为float ,比较将变为if (float > float) 。 我的问题是为什么首先需要将int变量提升为float ,是因为计算机比较容易比较两个普通数而不是试图找出每个数字的位代表然后比较它?
If I have something like this:
int i = 123; float f = 123.1; if (f > i) {} else {}The i will be promoted to a float and the comparison will become if (float > float). My question is why does the int variable needs to be promoted to a float in the first place, Is it because its easier for the computer to compare two plain numbers than trying to figure out what the bits of each number represent and then compare that?
最满意答案
因为“没有数字”。 计算机不会比较数字,也不能使用数字。 他们使用和比较位模式 。
事实位模式表示数字是由于我们用来将数字表示为位模式的“编码”。 一旦我们选择了编码,对数字的操作就会成为位模式的操作。 一旦我们选择了另一种编码,对数字的相同操作就会成为位模式的其他操作。
现在,如果您有10种可能的方式来表示数字,那么您应该支持100种可能的方式来执行二进制操作(如果您还想考虑结果,甚至可以支持1000种方法!)。
由于这不能扩展,你必须减少。 减少更简单的方法是通过将它们分成几部分来消除类似的事情:首先将所有数字转换为公共编码,然后对该编码进行操作并最终将结果转换回所需的数字。
这主要是由于可以容易地实现对具有相同编码的数字的操作,因为相同的规则适用于所有地方 ,并且这可以通过重用相同的电路来完成。
但为了实现这一点,必须选择“通用格式”,以便可以表示两个操作数。 并且将一个int表示到float中比将float表示为int更有成功的机会。
Because "There are no numbers". Computers don't compare numbers, and don't work with numbers. They work with, and compare, bit patterns.
The fact bit patterns represent numbers is due to the "encoding" we use to represent numbers as bit patterns. And once we choose an encoding, operations on numbers become operations on bit patterns. And once we choose another encoding, same operations on numbers become other operations on bit patterns.
Now, if you have 10 possible way to represent numbers, you should support 100 possible ways to do binary operations (or even 1000, if you also want to consider the result!).
Since this cannot scale, you have to reduce. And the simpler way to reduce is to eliminate similar things by splitting them into parts: first convert all all numbers to go into a common encoding, then operate on that encoding and eventually convert the result back to the desired one.
This is essentially due to the fact that operation on numbers having a same encoding can be implemented easily since same rules apply everywhere, and this can be done by reusing the same circuitry.
But for this to work, the "common format" must be chosen so that both the operands can be represented. And representing an int into a float has more chances to succeed than representing a float into an int.
更多推荐
发布评论