Arthur Oliveira
Arthur Oliveira

Reputation: 1

How do i add a value from a Console.ReadLine into an array?

I want to read a float value from the user and store that value in an array, so that i can then add it all and divide it by the amount of inputs that the user has given me, once they type in a value bellow 0.

using System;

class Program {
  public static void Main (string[] args) {

 float [] tt;
    
 int ct = 0;
 for (int i = 0; i>-1; i++); {

   float id = float.Parse(Console.ReadLine());


   if (id > -1) {
     ct++;
   } else {
     Console.WriteLine(id/ct);
   }


    }
  }
}

Upvotes: 0

Views: 954

Answers (1)

cg-zhou
cg-zhou

Reputation: 563

using System;

class Program
{
    public static void Main(string[] args)
    {
        float sum = 0;
        int ct = 0;

        while (true)
        {
            float id = float.Parse(Console.ReadLine());

            if (id > -1)
            {
                sum += id;
                ct++;
            }
            else
            {
                Console.WriteLine(sum / ct);
                break;
            }
        }

        Console.ReadKey();
    }
}

A better code is written as follows, and more checks are added here:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    public static void Main(string[] args)
    {
        var list = new List<double>();
        while (true)
        {
            var line = Console.ReadLine();
            if (!double.TryParse(line, out var number))
            {
                Console.WriteLine($"Can't parse number: {line}");
                return;
            }

            if (number < 0)
            {
                break;
            }

            list.Add(number);
        }

        Console.WriteLine("The average is: " + list.Average());
        Console.ReadKey();
    }
}

Upvotes: 2

Related Questions