Android Question What is the best way to code the multiplication of two integers?

BillMeyer

Well-Known Member
Licensed User
Longtime User
Welcome Noobie !!

Try this:

B4X:
Dim  Ans As Int
Dim Int1 As Int = 10
Dim Int2 As Int = 2

Ans = Int1 * Int2
Log("Your Answer Is: "&Ans)

' Division (/), Addition (+) and Subtraction (-) will work equally as well

Now, given the above, what would your answer be if:

2 + 10 / 2 = ?

6 or 7 ?

Enjoy !!
 
Upvote 0

udg

Expert
Licensed User
Longtime User
..and a nasty one:
B4X:
Dim a As Int = 1150100100 
Dim b As Int = 2
Dim c As Int
c = a *b
Log(c)

Would you bet on 2300200200 ?

Enjoy
 
Upvote 0

BillMeyer

Well-Known Member
Licensed User
Longtime User
..and a nasty one:
B4X:
Dim a As Int = 1150100100
Dim b As Int = 2
Dim c As Int
c = a *b
Log(c)

Would you bet on 2300200200 ?

Enjoy

I would but I get "Answer for c is: -1994767096"

Baffled - Has this got something to do with Intergers ? (2 to the base whatever I suppose)
If I change the Dim's to Long then I get the correct answer !!
And so many of us get caught out !!

Well done !!
 
Upvote 0

udg

Expert
Licensed User
Longtime User
Have a look here.
Int is 4 bytes signed so its range is -2147483648 to +2147483647; that means once it reaches one end it "wraps" to the other one ( 2147483647 + 1 = -2147483648).
Long type is 8 bytes long.
 
Upvote 0

BillMeyer

Well-Known Member
Licensed User
Longtime User
Have a look here.
Int is 4 bytes signed so its range is -2147483648 to +2147483647; that means once it reaches one end it "wraps" to the other one ( 2147483647 + 1 = -2147483648).
Long type is 8 bytes long.

Thank you Sir - Confirms my suspicions
 
Upvote 0
Top