Click here to Skip to main content
15,897,226 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Any advice on how to debug this code? Everything is fine except it outputs the wrong number. var average = total / count;
{
            var total = 0;
            double count = 0;
            int i = 0;
            double[] arr1 = new double[20];

            for (i = 0; i < 20; i++)
            {

                Console.Write("Enter a number: ");
                string input = Console.ReadLine();


                if (input == "0") break;
                arr1[i] = int.Parse(input);


                if (int.TryParse(input, out int value) && value >= 0) 
                {
                    count++;

                }

                total = input.Count(s => s > 1) + value;

            }

                var average = total / count;
                Console.WriteLine($"Average of all positive numbers: {average}");
                Console.ReadKey();
            
            }


What I have tried:

I have tried using while method but that didnt help.
Posted
Updated 21-Oct-21 14:17pm
v3
Comments
Patrice T 21-Oct-21 19:00pm    
Elaborate !
What are the values of count total and average ?
BillWoodruff 21-Oct-21 19:59pm    
repost of https://www.codeproject.com/Questions/5315673/How-do-I-fix-this-issue

however: requirement to ignore negative numbers is new.

1 solution

You are making progress ! Do use break-points and single-step (F11) through the code, observing exactly what happens.

Look how both total and count are updated only if there's a valid entry > 0/
double total = 0.0d;
double count = 0.0d;

double[] arr1 = new double[20];

for (int i = 0; i < 20; i++)
{
    Console.Write("Enter a number: ");
    string input = Console.ReadLine();

    if (input == "0") break;

    double parsedvalue = 0.0d;

    if (int.TryParse(input, out parsedvalue) && parsedvalue >= 0.0d) 
    {
        arr1[i] = int.Parse(input);
        total += parsedvalue;
        count++
    }

    // WHY ? ?total = input.Count(s => s > 1) + value;
}

double average = total / count;
Console.WriteLine($"Average of all positive numbers: {average}");
Console.ReadKey();
 
Share this answer
 
v2
Comments
Agar Gamez 22-Oct-21 7:44am    
Huge thanks! I was able to learn something from both of these posts :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900