繁体   English   中英

C# 数字数组

[英]C# array of numbers

所以我有这个 txt 文件,其中包含一组不同的数字。 如何让程序读取该文件并显示:

  • 文件中有多少个数字
  • 它的总和/垫积是多少
  • 最小值/最大值和平均值

到目前为止,我有这个:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace laboratorinis7
{
class Program
{
    static void Main(string[] args)
    {
        string skaiciai = "skaiciai.txt";
        string rodymas = File.ReadAllText(skaiciai);
        Console.WriteLine(rodymas);
        Console.ReadLine();
        string[] sa1 = rodymas.Split("\r\n".ToCharArray());

        string[] sa2 = new string[0];
        int y = 0;
        foreach (string s in sa1)
        {
            if (s == string.Empty) continue;
            string[] t = s.Split(' ');
            for (int x = 0; x < t.Length; ++x)
            {
                Array.Resize(ref sa2, sa2.Length + 1);
                sa2[y++] = t[x];
            }
        }

        foreach (string S in sa2)
        {
            Console.WriteLine(S);
        }

        Console.ReadLine();
    }
}
}

它显示 txt 文件内容,但没有数组。

您的代码不必要地复杂。 使用默认的 .Net 实现使您的代码可读和可理解。

string skaiciai = "skaiciai.txt";

string[] lines = File.ReadAllLines(skaiciai); // use this to read all text line by line into array of string

List<int> numberList = new List<int>(); // use list instead of array when length is unknown

for (int i = 0; i < lines.Length; i++)
{ 
    //if (s == string.Empty) continue; // No need to check for that. Split method returns empty array so you will never go inside inner loop.

    string[] line = lines[i].Split(' ');

    for (int j = 0; j < line.Length; j++)
    {
        string number = line[j];
        int n;
        if (int.TryParse(number, out n)) // try to parse string into integer. returns true if succeed.
        {
            numberList.Add(n); // add converted number into list
        }
    }
}

// Other way using one line linq to store numbers into list.
//List<int> numberList = lines.SelectMany(x => x.Split(' ')).Select(int.Parse).ToList();

int totalNumbers = numberList.Count;
int sum = numberList.Sum();
int product = numberList.Aggregate((a, b) => a*b);
int min = numberList.Min();
int max = numberList.Max();
double average = sum/(double)totalNumbers;

告诉我您的文本文件是否包含双数,因为那么您必须使用双精度类型而不是整数。

还要尝试为变量使用合适的名称。 tt1这样的名称而不是linesline并没有真正描述任何东西,并且会使您的代码更难理解。

如果您有大量数字列表,您可能必须使用long类型或double如果它们有小数部分。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM