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

C#.NET ProgrammingASP.NET

Avatar of undefined
Last Comment
AndyAinscow

8/22/2022 - Mon
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.
it_saige

Consider the order of operations...

-saige-
ASKER
Camillia

Should be  (a+b)/2?
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
it_saige

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

-saige-
SOLUTION
Fernando Soto

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
ASKER CERTIFIED SOLUTION
Log in to continue reading
Log In
Sign up - Free for 7 days
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Chris Stanyon

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!
OriNetworks

come on people this is homework. If we give 100% of the answer we aren't helping.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
SOLUTION
Log in to continue reading
Log In
Sign up - Free for 7 days
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Scott C

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.
ASKER
Camillia

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.
OriNetworks

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.
Your help has saved me hundreds of hours of internet surfing.
fblack61
David Johnson, CD

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.
AndyAinscow

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.
kaufmed

OK, I think I've had enough energy drink to take a stab. Is it the inclusion of the single/float literal?
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
it_saige

@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_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 -Capture.JPG-saige-
kaufmed

@it_saige

Right. I was just making sure that my lack of sleep wasn't making me overlook something else   ; )
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
ASKER
Camillia

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.
AndyAinscow

@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, CD

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
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
AndyAinscow

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.