为什么操作符的操作数需要是相同类型的? [英] Why the operands of an operator needs to be of the same type?

查看:133
本文介绍了为什么操作符的操作数需要是相同类型的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的:

int i = 123;
float f = 123.1;

if (f > i) {} else {}

i 将被提升为 float ,比较将变为 if(float> float )。我的问题是为什么 int 变量需要首先提升为 float ,是因为它的更容易计算机比较两个纯数字,而不是试图找出每个数字的位代表什么,然后比较?

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?

推荐答案

因为没有数字。计算机不比较数字,不使用数字。

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.

你有10种可能的方式来表示数字,你应该支持100种可能的方式来做二进制操作(甚至1000,如果你也想考虑结果!)。

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.

但是为了这个工作,必须选择通用格式,以便可以表示两个操作数。并且将一个int表示为一个float有更多的机会成功比将一个float表示为int。

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.

这篇关于为什么操作符的操作数需要是相同类型的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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