1

This is a example equation which I want to be solved:

let equation = (5-2) * (10-5) / (4-2) * (10-5)
print (equation)
//35

The result which is printed is 35. But the right result would be 1,5. Whats wrong?

Hamish
  • 78,605
  • 19
  • 187
  • 280
E. Tess
  • 17
  • 2

3 Answers3

2

your expression is incorrect I hope you want the result 1.5 put '(' correctly * and / Precedence to execution are same but () is greater than * and /

let equation = ((5-2) * (10-5)) / ((4-2) * (10-5))
print (equation)

if you put the multiplication in another '()' then you will get result one perhaps the right part is integer so its auto conver to integer type

let equation = Double ( (5 - 2) * (10 - 5)) / Double ((4 - 2) * ( 10 - 5 ))
print (equation)

this code will print 1.5

Just look out operators Precedence in programming language

Araf
  • 510
  • 8
  • 32
0

This should work:

let numerator: Double = (5-2) * (10-5)
let denumerator: Double = (4-2) * (10-5)

Fist you calculate the numerator and denumerator. And finally the result:

print(result)
let result: Double = numerator/denumerator
//1.5
l30c0d35
  • 777
  • 1
  • 8
  • 32
0

As @araf has answered you should look out for the operator precedence in programming language.

Which follow a simple rule of the BODMAS evaluated in following order:

  1. Brackets
  2. Orders
  3. Division and Multiplication (left to right)
  4. Addition and Subtraction (left to right)

In your scenario:

let equation = (5-2) * (10-5) / (4-2) * (10-5)

the output is as follows:

3*5/2*4 = 15/2*5 = 7*5 = 35

@L.Stephan has suggested a better approach of calculating numerator and denumerator separately and then perform the division part.

To know more you can check this link:

Amit
  • 4,837
  • 5
  • 31
  • 46