Why it gives wrong output | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why it gives wrong output

print(1+99+1-100/2*4) I want output 2 but it gives -99.0

15th Jun 2017, 7:03 AM
Suresh U
Suresh U - avatar
8 Answers
+ 1
That's why parentheses and order of operations are so important.... :) print(1+99+1-100/2*4) 1+99+1 = 101 100/2*4 = 200 101 - 200 = -99 So the output is actually correct :) And just to nitpick a little @visph :) - x/2*4 is not always x*2 :) >>> 5/2*4 8 In python2, the slash operator performs integer division. Which leads to this ugly and confusing result. So it was changed in python3: >>> 5/2*4 10.0
15th Jun 2017, 8:40 AM
Bogdan Sass
Bogdan Sass - avatar
+ 4
@Bogdan: I cannot give you wrong... It's a trap, so your information is certainly useful for many users here (even for me: I wasn't remember that in C++ (I just pseudo learned C# here, so not surprising if I don't also remember for it) the division was integer by default... and while I write it I understand my mistake: this isn't a default behaviour, this is a context behaviour, as in every language with hard typed variable: expected result is integer as variable type is declared as integer, so integer division is relatively logically applied ^^ but this is an explicit context ;P )
15th Jun 2017, 9:07 AM
visph
visph - avatar
+ 3
@Bogdan: integer division is a special case, not really related to this context, as Py3 is used (and teached) on Sololearn ;) (without specification, I read a mathematical expression, so working in decimal, not integer)
15th Jun 2017, 8:45 AM
visph
visph - avatar
+ 2
:D I love this kind of expression: num/2*4... ... wich could easily be reduce to: num*2 :P
15th Jun 2017, 8:10 AM
visph
visph - avatar
+ 1
Your code is incorrect print(1+99-49/2*4) //output 2.0
15th Jun 2017, 7:16 AM
Lord Krishna
Lord Krishna - avatar
+ 1
print(1+99-49/2*4) // 1+99=100 //49/2=24.5 * 4 = 98 // 100 -98 = 2
15th Jun 2017, 7:24 AM
Lord Krishna
Lord Krishna - avatar
+ 1
@visph - ok, python2 is not taught on SoloLearn. Then how about C++ or C#? :) int main() { int a = (5/2)*2; cout<<a; return 0; } Or: static void Main(string[] args) { int a = (5/2)*2; Console.WriteLine(a); } They both print "4". I agree with you that mathematically speaking, x/2*4 = x*2 . I'm just pointing out these "strange behaviours" so that people know of them and are not surprised when they first encounter them :)
15th Jun 2017, 8:57 AM
Bogdan Sass
Bogdan Sass - avatar
0
Can you explain your answer?
15th Jun 2017, 7:17 AM
Suresh U
Suresh U - avatar