What’s wrong with this code? #2

Check out the following code snippet:

    static decimal Division(int a, int b) { return a / b; }

kick it on DotNetKicks.com

Comments (7) imported from www.ekampf.com/blog/:

Sunday, September 02, 2007 9:46:22 AM (GMT Daylight Time, UTC+01:00)

divide with zero..

bb king

Sunday, September 02, 2007 10:54:57 AM (GMT Daylight Time, UTC+01:00)

Absent casting to decimal in return.

HaGever

Sunday, September 02, 2007 2:18:37 PM (GMT Daylight Time, UTC+01:00)

Casting has nothing to do with it. The code compiles and runs without exceptions unless you divide by zero as specified in the first comment.
But division by zero is not the only thing wrong here…

Eran Kampf

Sunday, September 02, 2007 4:28:29 PM (GMT Daylight Time, UTC+01:00)

1 in 5 Americans can divide by 0, such as. Just ask Miss South Carolina.

Brennan Stehling

Sunday, September 02, 2007 6:06:58 PM (GMT Daylight Time, UTC+01:00)

2Eran Kampf
Casting necessary here!
Define
a = 3
b = 2
Without casting your result will be 1, but with casting – 1.5
Int/Int return int, but (decimal)int/int = decimal
P.S.I don’t remind a division inasmuch as that this is trivial.
😉 Good luck

HaGever

Sunday, September 02, 2007 6:40:16 PM (GMT Daylight Time, UTC+01:00)

Exactly!
You found the second point I was aiming at – dividing integers results an integer. so given a=1 and b=2 the method will return 0 and not 0.5 as expected.
On your first comment I understood you want to cast the return value which means doing (decimal)(a/b) which is still wrong.
You need to cast a and b before dividing by doing (decimal)a / (decimal)b or by doing what you said in the second comment (decimal)a / b which actually casts a to decimal and then divides it by b.
I guess the 2nd snippet was too easy compared to the 1st :\
Regards,
Eran

Eran Kampf

Friday, November 23, 2007 9:23:52 AM (GMT Standard Time, UTC+00:00)

This is great! One question: Is there any way around the authentication issue? I have a portal which requires a login/password. Am I out of luck? –thanks

WOW GOLD

You may also like...