Link to home
Start Free TrialLog in
Avatar of Camillia
CamilliaFlag for United States of America

asked on

Is there a bug in this code?

I'm taking some online coding tests and came across this one. It says it has bugs in it. I copied it to a console app and it runs fine.

What's wrong with this code?

using System;

public class MathUtils
{
    public static double Average(int a, int b)
    {
        return a + b / 2;
    }
    
    public static void Main(string[] args)
    {
        Console.WriteLine(Average(2, 1));
    }
}

Open in new window

Avatar of OriNetworks
OriNetworks

the program may compile and run but does it work?

think about what the program should be doing and run some sample tests against it to see that it works as expected.
Consider the order of operations...

-saige-
Avatar of Camillia

ASKER

Should be  (a+b)/2?
Correct...  Now consider what integer division does to the result...

-saige-
SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Definition of a bug from Wiki:

A software bug is an error, flaw, failure or fault in a computer program or system that causes it to produce an incorrect or unexpected result, or to behave in unintended ways.

Your code definitely has a flaw that will cause an unexpected result!
come on people this is homework. If we give 100% of the answer we aren't helping.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
saige didn't give the answer...merely guided.

syntax errors are easy....logic errors are the hard ones.

Fernando gave the solution but OP found it before that.
It's not homework. It's a website for coding tests but the instructions aren't clear. I'll post the link in the morning.
I misspoke and apologize. A link is not necessary but you can accept the answer of any experts that you believe helped guide you/answer the question. I wish you luck in your learning.
if the anwer didn't jump out at you then you need to start with the basics i.e. mathemetics order of operation. You have a long way to go. but first you have to understand the basics. or at least step through the program operation checking the results and then stopping when the expected result is not the result shown in the debugger.
And now who will spot the second bug still unexplained nor mentioned?

ps.  The code from it_saige has cured it without it being discussed, that from Fernando Soto still has it.
OK, I think I've had enough energy drink to take a stab. Is it the inclusion of the single/float literal?
@Andy - did you miss my post here: http:/Q_28906695.html#a41388763
Correct...  Now consider what integer division does to the result...
I'll give you that I left the response as open-ended, but that was the intention, to get Camilla to think about the operation (above and beyond just the order).

-saige-
@Kaufmed,

Essentially, it's more about ensuring that you do not use integer division (hence the single/float literal).  
Consider the following:
using System;
using System.Linq;

namespace EE_Q28906695
{
	class Program
	{
		readonly static int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

		static double Average(params int[] values)
		{
			int total = 0;
			foreach (int value in values)
				total += value;
			return total / Convert.ToDouble(values.Length);
			// The above could easily be accomplished in linq using the Enumerable.Average() method; e.g. -
			// values.Average();
		}

		static void Main(string[] args)
		{
			Console.WriteLine("Average of {{{0}}} is: {1}", string.Join(", ", Array.ConvertAll(numbers.Take(3).ToArray(), x => x.ToString())), Average(numbers.Take(3).ToArray()));
			Console.WriteLine("Average of {{{0}}} is: {1}", string.Join(", ", Array.ConvertAll(numbers, x => x.ToString())), Average(numbers));
			Console.WriteLine("Average of {{{0}}} is: {1}", string.Join(", ", Array.ConvertAll(numbers.Skip(7).ToArray(), x => x.ToString())), Average(numbers.Skip(7).ToArray()));
			Console.ReadLine();
		}
	}
}

Open in new window

Which produces the following output -User generated image-saige-
@it_saige

Right. I was just making sure that my lack of sleep wasn't making me overlook something else   ; )
This is the site http://www.testdome.com/

That was an easy one to solve. I had a mental block (I was eating pizza and chatting...serioulsy :))

Some sites I find are good but some are just thrown together. It's good either way...I like taking online tests like that. This is because about 2 years ago...I had to take an online test for an interview...and I panicked and bombed it. I decided to practice and get comfortable at taking tests.

Any other sites you guys have that could recommend would be great.
@it-saige, sorry I missed that line.
Yes, I did mean that integer division such as (a+b)/2 would still not produce the correct result in numerous cases when a non integral result is being returned.
any result of a+b that is not an even number will not give the correct answer
a = 2 b = 4 a+b = 6 /2 = 3 correct
a = 1 b = 4 a+b = 5 /2 = 2 incorrect correct answer is 2.5
In some ways this is quite a good question.  There is a very obvious bug in it but there is then a rather more subtle bug that could easily be overlooked and if someone doesn't make a good test it might not get noticed.  Also both bugs are on the same line of code.