0

c ++ and JavaScript have different answers? Check this..

A= 20, B = 30 mix = (a/b+5)*3+b-a*9%a This is answered differently in both c ++ and javascript. Why does this happen? As well as calculator, the answer is different..

24th Jan 2021, 7:11 AM
jaydip devaliya
jaydip devaliya - avatar
9 Respuestas
+ 7
jaydip devaliya In C++ or Java, 20 / 30 will always be 0 because 20 is less than 30 and data type is int so int always gives numeric value. So here (a / b + 5) * 3 = (0 + 5) * 3 = 15 In JavaScript 20 / 30 will give 0.6666667 because JavaScript automatically handle data type, we don't need to define the data type. So here (a / b + 5) * 3 = (0.6666667 + 5) * 3 = (5.6666667) * 3 = (17.0000001) = 17 In C++ or Java if you do like this int a = 20; int b = 30; cout << (double) 20 / 30; then you get 0.6666667
24th Jan 2021, 8:10 AM
A͢J
A͢J - avatar
+ 3
I guess your c++ code is: int a = 20, b = 30, mix = ... in this case, (a/b+5)*3 == 15 (integer division) in c++, but == 17 in javascript (float division) you could have same result by doing: float a = ... anyway, if you declare variables as float, you must cast 'a' to int for last modulo (%) operation: float a = 20, b = 30, mix = (a/b+5)*3 + b - (int) (a*9) % (int) a;
24th Jan 2021, 7:56 AM
visph
visph - avatar
+ 3
I Am AJ ! .... Ohh Thank you now I understand.🧑‍💻☺️
24th Jan 2021, 8:13 AM
jaydip devaliya
jaydip devaliya - avatar
+ 1
assuming you declare a, b and mix as int in your c++ code, (a/b+5)*3 result as 15 (integer division), while 17 in js (float division)... if you declare them as float, you'll get same result...
24th Jan 2021, 7:43 AM
visph
visph - avatar
+ 1
a = 20; b = 30; mix = (a / b + 5) * 3 + b - a * 9 % a = (20 / 30 + 5) * 3 + 30 - 20 * 9 % 20 = ((((20 / 30) + 5) * 3) + 30) - ((20 * 9) % 20) = … C++ move (with int: only whole numbers): … = (((0 + 5) * 3) + 30) - ((20 * 9) % 20) = ((5 * 3) + 30) - ((20 * 9) % 20) = (15 + 30) - ((20 * 9) % 20) = 45 - ((20 * 9) % 20) = 45 - (180 % 20) = 45 - 0 = 45 JavaScript move (with Number: any real number; anyways, the type is defined automatically): … = (((0.66666666… + 5) * 3) + 30) - ((20 * 9) % 20) = ((5.66666666… * 3) + 30) - ((20 * 9) % 20) = (17 + 30) - ((20 * 9) % 20) = 47 - ((20 * 9) % 20) = 47 - (180 % 20) = 47 - 0 = 47
24th Jan 2021, 8:19 AM
#0009e7 [get]
#0009e7 [get] - avatar
+ 1
get .... Ohh Thank you so much now I understand this .!
24th Jan 2021, 8:22 AM
jaydip devaliya
jaydip devaliya - avatar
0
get ... I have assigned its value to just for information
24th Jan 2021, 7:39 AM
jaydip devaliya
jaydip devaliya - avatar
0
visph .... I don't understand what you told me, can you try to understand in a simple language .... 😥🤷‍♂️
24th Jan 2021, 7:51 AM
jaydip devaliya
jaydip devaliya - avatar
0
visph Ohh yas🙂
24th Jan 2021, 8:22 AM
jaydip devaliya
jaydip devaliya - avatar