【问题标题】:How do i add a value from a Console.ReadLine into an array?如何将 Console.ReadLine 中的值添加到数组中?
【发布时间】:2021-12-27 05:30:17
【问题描述】:

我想从用户那里读取一个浮点值并将该值存储在一个数组中,这样我就可以将它全部添加并除以用户给我的输入量,一旦他们输入了一个值低于 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);
   }


    }
  }
}

【问题讨论】:

标签: c# arrays


【解决方案1】:
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();
    }
}

更好的代码写如下,这里增加了更多的检查:

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();
    }
}

【讨论】:

  • 是的,我已经构建并测试了代码。循环永远不会停止。我在这里遇到了一个问题。尽量不要改代码,让提问的人更容易理解,或者用最好的写法…… List 平均就够了,不过我觉得还不够他/她已经学习了 LINQ。
  • 好的,我已经更新了答案...现在当用户输入负数(
猜你喜欢
  • 2012-02-27
  • 2011-01-10
  • 2021-09-13
  • 1970-01-01
  • 2016-07-22
  • 2020-05-21
  • 2014-09-11
  • 1970-01-01
  • 2012-02-24
相关资源
最近更新 更多