趣味挑战:写一个 2 + 2 = 5 的程序

5月30日,有网友在 StackExchange 提了一个问题:

请写一段程序,使其看似 2 加 2 等于 5。这是一个骗人的测试,但程序不能有任何错误,注意内存漏洞。输入操作可选。把 2+2 重定义为 5 就没那么有创意了。想都别想哈,试试其他方法呗。

下面整理了部分程序员的回帖:

 

1. Java

解释:

You need to change it even deeper than you can typically access. Note that this is designed for Java 6 with no funky parameters passed in on the JVM that would otherwise change the IntegerCache.

Deep within the Integer class is a Flyweight of Integers. This is an array of Integers from −128 to +127. cache[132] is the spot where 4 would normally be. Set it to 5.

鼠标选中上面”空白“区域,可查看白色字体的解释。

在线测试:http://ideone.com/o1h0hR

2. C 语言

解释:

把滚动条往右拖啊!!!

鼠标选中上面”空白“区域,可查看白色字体的解释。

在线测试:http://ideone.com/16PScH#view_edit_box

 

3. Haskell

 

4. BBC Basic

解释:

This actually prints the number 4, but the VDU 23 redefines the font for ASCII 52 so that it looks like a 5 instead of a 4. Screen mode 6 was selected for aesthetic reasons (characters of a reasonable size.)  

鼠标选中上面的”空白“区域,可查看白色字体的解释。

 

5. Java

输出结果:

解释:

No, seriously, you always have to round your doubles. 15 isn’t enough digits to show that the two()method actually produces 2.0000000000000004 (16 is enough, though).

In the raw Hex representations of the numbers, it’s only a 1 bit difference (between 4000000000000001 and 4000000000000000)… which is enough to make the Math.ceilmethod return 5, not 4.

鼠标选中上面的”空白“区域,可查看白色字体的解释。

 

6. Python

解释:

Like Java, CPython uses the same memory location for any copy of the first few small integers (0-255 if memory serves). This goes in and directly edits that memory location via ctypespatch is just an obfuscated "12-7", a string with len 4, which eval‘s to 5.

鼠标选中上面的”空白“区域,可查看白色字体的解释。

 

7. JavaScript

在线测试:http://jsfiddle.net/qhRJY/

解释:

Both H (Latin letter capital h) and Η (Greek letter capital eta) are set to the global scope because they were not defined as local to the functions with the var keyword. While they look similar, they are actually 2 different variables with 2 different values. Using Ctrl+F in your browser you will find that Η (eta) shows up significantly less than H (h) on this page.

鼠标选中上面的”空白“区域,可查看白色字体的解释。

8. Bash

输出:

解释:

 

9. PHP

输出:

解释:

10. BrainFuck

在线测试:http://esoteric.sange.fi/brainfuck/impl/interp/i.html

 

更多其他回复:http://codegolf.stackexchange.com/questions/28786/write-a-program-that-makes-2-2-5

打赏支持我翻译更多好文章,谢谢!

打赏译者

打赏支持我翻译更多好文章,谢谢!

任选一种支付方式

2 收藏 4 评论

关于作者:黄利民

伯乐在线联合发起人,关注 IT 和互联网。 个人主页 · 我的文章 · 97 ·  

相关文章

可能感兴趣的话题



直接登录
最新评论
跳到底部
返回顶部