We help IT Professionals succeed at work.

Is there a bug in this code?

Camillia
Camillia asked
on
7,208 Views
1 Endorsement
Last Modified: 2016-01-02
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

Comment
Watch Question

CERTIFIED EXPERT

Commented:
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.
it_saigeDeveloper
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
Consider the order of operations...

-saige-
CERTIFIED EXPERT

Author

Commented:
Should be  (a+b)/2?
it_saigeDeveloper
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
Correct...  Now consider what integer division does to the result...

-saige-
Fernando SotoRetired
CERTIFIED EXPERT
Distinguished Expert 2017
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
Developer
CERTIFIED EXPERT
Distinguished Expert 2019
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
CERTIFIED EXPERT
Most Valuable Expert 2018
Distinguished Expert 2019

Commented:
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!
CERTIFIED EXPERT

Commented:
come on people this is homework. If we give 100% of the answer we aren't helping.
CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
Scott CSenior Engineer
CERTIFIED EXPERT

Commented:
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.
CERTIFIED EXPERT

Author

Commented:
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.
CERTIFIED EXPERT

Commented:
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.
David Johnson, CDSimple Geek from the '70s
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
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.
AndyAinscowFreelance programmer / Consultant
CERTIFIED EXPERT

Commented:
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.
CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015

Commented:
OK, I think I've had enough energy drink to take a stab. Is it the inclusion of the single/float literal?
it_saigeDeveloper
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
@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-
it_saigeDeveloper
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
@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 -Capture.JPG-saige-
CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015

Commented:
@it_saige

Right. I was just making sure that my lack of sleep wasn't making me overlook something else   ; )
CERTIFIED EXPERT

Author

Commented:
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.
AndyAinscowFreelance programmer / Consultant
CERTIFIED EXPERT

Commented:
@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.
David Johnson, CDSimple Geek from the '70s
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
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
AndyAinscowFreelance programmer / Consultant
CERTIFIED EXPERT

Commented:
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.

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.