为什么运算符的操作数必须属于同一类型?(Why the operands of an operator needs to be of the same type?)

编程入门 行业动态 更新时间:2024-10-12 16:22:45
为什么运算符的操作数必须属于同一类型?(Why the operands of an operator needs to be of the same type?)

如果我有这样的事情:

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.

更多推荐

本文发布于:2023-08-01 03:23:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1353918.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:运算符   类型   操作   type   operands

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!