+ 2

Why following code gives me wrong output??

https://code.sololearn.com/We04WMFZVdlE/?ref=app in above script , line no 29 gives wrong value for n. I tried same logic using other languages. it works fine ... Even when I execute that line separately , it gives correct output. Plz help to correct this code of reverse floyd triangle.

19th Apr 2018, 5:49 PM
Manorama
Manorama - avatar
8 odpowiedzi
+ 5
Duncan You're not too far off from the correct explanation. The issue here is the + operator will behave differently depending on the variable type being a string or a number. If a value on either side of the + operator is a string type, both values will be treated as strings resulting in a concatenation of the two values. Otherwise, if both values are number types, then the sum of the values will be the result. After reviewing the latest code, the Floyd's Triangle function multiplies the value of r, rather than using the + operator. Therefore, this code works without using parseInt(). In Javascript, using any other arithmetic operator will behave the same for both numeric strings and actual number types.
27th Apr 2018, 4:22 AM
David Carroll
David Carroll - avatar
+ 3
r is not an integer but a string. (r + 1) makes 41 if the input is 4. I don't know JavaScript well but I think that is what happened. Add this after the input and before the calculation: r = Number (r);
19th Apr 2018, 6:38 PM
Paul
Paul - avatar
+ 2
Duncan ,Paul Jacobs Thank you I just make use of r=parseInt() in reverse triangle ,& it works fine ... but I am confused , I don't use parseInt in floyd triangle ( line no 13), but still it works fine ... So why there is no need to convert r to number ?
19th Apr 2018, 8:58 PM
Manorama
Manorama - avatar
+ 2
okk Duncan
19th Apr 2018, 9:11 PM
Manorama
Manorama - avatar
+ 2
Thanks David Carroll , good to know the missing link.
27th Apr 2018, 4:24 AM
Duncan
Duncan - avatar
+ 1
Manorama see my note re just using n=r; The arithmetic seems to be changing the behaviour of the JavaScript and treating the value from the document as a String. Don't know why though, a more experienced JavaScript SoloLearner may know.
19th Apr 2018, 9:01 PM
Duncan
Duncan - avatar
+ 1
thank you David Carroll nice explanation
27th Apr 2018, 4:29 AM
Manorama
Manorama - avatar
0
I think Paul Jacobs is right. I used parseInt when getting 'r' and it worked when I tested with 3 rows r=parseInt(document.getElementById("rows").value); Something to do with the arithmetic as I did the following instead of the equation and although the wrong answer, the numbers made sense. n=r; Don't know why but I also noticed that I couldn't do a reverse triangle unless I'd done a forward one first. This may be changing the behaviour of your code?
19th Apr 2018, 7:27 PM
Duncan
Duncan - avatar