-2

Write a C# program to retrieve the values from the text file and print the average of the values,formatted with two decimal places.

So I have already coded and created a text file named "averages.txt" which there are 4 numbers in the file, and my program is already retrieving data in my text file and outputting the values.

What I'm having trouble with is where I need to find the averages of the 4 numbers in the file and then formatting the numbers into 2 decimal places.

My code:

    static void Main(string[] args)
    {
        string innerNum;
        string outerNum = "";

        if (File.Exists("averages.txt"))
        {
            try
            {
                StreamReader inFile = new StreamReader("averages.txt");
                while ((innerNum = inFile.ReadLine()) != null)
                {
                    outerNum += innerNum + "\n";
                }
                Console.WriteLine(outerNum);


            }
            catch (System.IO.IOException e)
            {
                Console.WriteLine("IO Exception: " + e.Message);
            }
        }
            else
            {
                Console.WriteLine("The File Does Not Exist.");
            }

        Console.Write("Press Enter to Exit.");
        Console.ReadKey();
    }
}

}

Minh Nguyen
  • 11
  • 1
  • 2
  • 4
  • 1
    Consider how you actually get an average. You need to add the numbers, and add a counter to indicate how many numbers you have, then divide the first by the second. You're currently displaying the contents of the file, but you really haven't even attempted to get an average yet. – Grant Winney Nov 08 '14 at 16:38
  • 1
    You need to `parse` your string into a number (integer, decimal, etc...) – Nathan Koop Nov 08 '14 at 16:39
  • Yes to anyone who thinks it's an homework assignment, yes it is. C# is still difficult language to learn for me. But thanks for the help. – Minh Nguyen Nov 08 '14 at 16:56

2 Answers2

0

You have to Parse a string to double. Please remember that below solution will work only if each of line has number. You should add validation, Exception handling, etc.

You may output number with 2 decimal places by String.Format("{0:N2}", ...). http://msdn.microsoft.com/en-us/library/system.string.format(v=vs.110).aspx

static void Main(string[] args) {
    string innerNum;
    string outerNum = "";
    double sum = 0;
    int count = 0;
    if (File.Exists("averages.txt")) {
        try {
            StreamReader inFile = new StreamReader("averages.txt");
            while ((innerNum = inFile.ReadLine()) != null) {
                try {
                    outerNum += innerNum + "\n";
                    sum += double.Parse(innerNum);
                    count++;
                } catch(Exception e) {}
            }
            Console.WriteLine(outerNum);
        } catch (System.IO.IOException e) {
            Console.WriteLine("IO Exception: " + e.Message);
        }
    }  else {
        Console.WriteLine("The File Does Not Exist.");
    }
    Console.WriteLine("Average is : " + String.Format("{0:N2}",sum/(double)count));

    Console.Write("Press Enter to Exit.");
    Console.ReadKey();
}
nosbor
  • 2,826
  • 3
  • 39
  • 63
0

I answer this assuming this is a homework and your professor will not accept this Linq solution as an answer.

var avg = File.ReadAllText("averages.txt")
              .Split(" \t\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
              .Average(x => double.Parse(x, CultureInfo.InvariantCulture));

Console.WriteLine("AVG: {0:0.00}", avg);
EZI
  • 15,209
  • 2
  • 27
  • 33