Jump to content
MrGrj

PHP Challenge [easy] - funny task

Recommended Posts

  • Active Members

Fara a rula urmatorul cod si fara a cauta pe internet, ce va afisa aceasta linie de cod ?

Argumentati raspunsul dat. :)


<?php echo (int) ( (0.1 + 0.7) * 10); ?>

Solver:

- Ganav.

Raspuns complet (adaugat la ce a zis Ganav):

"IEEE 754 cannot be used for 0.1 as well as 0.7 ... so the float point addition becomes 0.799(9...) x 10 = 7.99(9...) and int typecast truncates the digits after decimal => 7 "

Raspuns dat:

Din cate stiu in PHP (int) rotunjeste in jos. Adica 0.1 nu este 0.1 si 0.1 - e unde e este un numar subunitar care este folosit pentru a reda precizia. Deci 0.1 este < 0.1, la fel si cu 0.7. De aici rezulta ca 0.1 + 0.7 < 0.8. Analog, 10 * ( 0.1 + 0.7) < 10 * 0.8. (int) rotunjind in jos ajunge la 7(valoarea intreaga imediat mai mica ca si 8).
Edited by MrGrj
Link to comment
Share on other sites

0.7? Din cate stiu in PHP (int) rotunjeste in jos. Adica 0.1 nu este 0.1 si 0.1 - e unde e este un numar subunitar care este folosit pentru a reda precizia. Deci 0.1 este < 0.1, la fel si cu 0.7. De aici rezulta ca 0.1 + 0.7 < 0.8. Analog, 10 * ( 0.1 + 0.7) < 10 * 0.8. (int) rotunjind in jos ajunge la 7(valoarea intreaga imediat mai mica ca si 8).

  • Upvote 1
Link to comment
Share on other sites

Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9999999999999991118....

Mai mult detalii in chenarul roz de aici: PHP: Floating point numbers - Manual

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • Create New...