趣味挑戰:寫一個 2 + 2 = 5 的程式

黃利民發表於2014-06-26

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 + 2 = 5 的程式 趣味挑戰:寫一個 2 + 2 = 5 的程式

相關文章