繁体   English   中英

如何从文本文件中引入数字并在 c# 中对它们进行数学运算

[英]How do I bring in numbers from a text file and do math on them in c#

我是 C# 的新手。 我正在尝试将 txt 文件中的数字带入我的程序并将它们相乘。 文本文件的格式如下:

1
2
3
4
5
6
7
8
9
10

我需要该程序执行1x2x3x4x5x6x7x8x9x10=3628800

这是一个包含 200 万个不同数字的列表。

我可以让它输出到文本文件,而不是输入。 我环顾四周,并没有真正看到答案。

谢谢。

你可以用几行代码来做到这一点。

var lines = File.ReadLines(fileName);
var collection = new List<int>();

foreach (var line in lines)
{
   collection.AddRange(line.Split(' ').Select(n => Convert.ToInt32(n)));  
}

var result = collection.Distinct().Aggregate((i, j) => i * j); // remove distinct if you don't want eliminate duplicates.

你可以试试这个

string value1 = File.ReadAllText("file.txt");
int res = 1;
var numbers = value1.Split(' ').Select(Int32.Parse).ToList();
for(int i=0;i<numbers.Count;i++)
{
    res = res * numbers[i];
}
Console.WriteLine(res);
var numbers = File.ReadAllText("filename.txt").Split(' ').Select(int.Parse); // Read file, split values and parse to integer
var result = numbers.Aggregate(1, (x, y) => x * y); // Perform multiplication

您想将 200 万个数字相乘,但有一个问题。

问题是内存限制。 要保存一个大数字,您必须在System.Numerics命名空间中使用BigInteger类。

您可以通过在项目顶部添加 Using 关键字来使用此参考。

using System.Numerics;

如果编译器无法识别Numerics 则您需要添加对System.Numerics.dll的程序集引用。

您的代码应如下所示。

string inputFilename = @"C:\intput.txt"; // put the full input file path and name here.

var lines = File.ReadAllLines(inputFilename); // put text lines into array of string.

BigInteger big = new BigInteger(1); // create the bigInt with value 1.

foreach (var line in lines) // iterate through lines
{
    big *= Convert.ToInt32(line); // Multiply bigInt with each line.
}

string outputFilename = @"C:\output.txt"; // put the full output file path and name here

File.WriteAllText(outputFilename, big.ToString()); // write the result into text file

这可能需要很长时间才能完成。 但这一切都取决于正在运行的硬件。 在此任务期间,您可能会遇到内存溢出异常,这取决于您拥有的内存量。

暂无
暂无

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

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