我正在尝试学习如何从文件中表示 C# 货币的数字列表中获取总和

本文关键字:货币 表示 列表 获取 数字 文件 学习 | 更新日期: 2023-09-27 17:56:55

我正在尝试从代表货币金额的文件中获取数字列表的总和。我无法让它工作,所以我在我的代码中创建了一个数组,并以这种方式让它为我的作业工作;但我仍然想知道如何自己编程以备将来参考。这是我编写的代码的副本,文件Sales.txt的值是:

1245.67
1189.55
1098.72
1456.88
2109.34
1987.55
1872.36

这是代码的副本:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace Lab7._2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        // ReadScore method
        private void ReadSales(List<decimal> salesList)
        {
            try
            {
                // Open File Sales.txt
                StreamReader inputFile = File.OpenText("Sales.txt");
                // Read the sales into the list.
                while (!inputFile.EndOfStream)
                {
                    salesList.Add(decimal.Parse(inputFile.ReadLine()));
                }
                // Close the file
                inputFile.Close();
            }
            catch (Exception ex)
            {
                // Display an error message
                MessageBox.Show(ex.Message);
            }
        } 
        // DisplaySales method displaying to ListBox
        private void DisplaySales(List<decimal> salesList)
        {
            foreach (decimal sales in salesList)
            {
                runningTotalListBox.Items.Add(sales);
            }
        }
        // The average method returns the average of the values
        private double Average(List<decimal> salesList)
        {
            decimal total = 0;  //Accumulator
            double average; // to hold the average
            // Calculate the total of the sales
            foreach (decimal sales in salesList)
            {
                total += sales;
            }
            // Calculate the average of the scores.
            average = (double)total / salesList.Count;

            // Return average.
            return average;
        }


        private void calButton_Click(object sender, EventArgs e)
        {
            double averageSales; // To hold the average sales
            // Create a list to hold the sales
            List<decimal> salesList = new List<decimal>();
            // create decimal array
            double[] units = { 1245.67, 1189.55, 1098.72, 1456.88, 2109.34, 1987.55,        1872.36 };
            // Declair and initilize an accululator variable.
            double totals = 0;
            // Step through array adding each element
            for (int index = 0; index < units.Length; index++)
                {
                totals += units[index];
                }

            // Read the sales
            ReadSales(salesList);
            // Display Sales
            DisplaySales(salesList);
            // Display Total
            outputLabel.Text = totals.ToString();
            // Display Average Sales Cost
            averageSales = Average(salesList);
            averageCostLabel.Text = averageSales.ToString("n1");
        }



        private void button2_Click(object sender, EventArgs e)
        {
            // Close the window
            this.Close();
        }
    }
}

我正在尝试学习如何从文件中表示 C# 货币的数字列表中获取总和

批量读取所有行的更简单方法:

List<decimal> values = File.ReadAllLines("Sales.txt")
                           .Select(s => decimal.Parse(s, CultureInfo.InvariantCulture))
                           .ToList();

在您的代码中:

private void ReadSales(List<decimal> salesList)
{
    salesList.AddRange(File.ReadAllLines("Sales.txt")
                           .Select(s => decimal.Parse(s, CultureInfo.InvariantCulture)));
}

您可以使用 LINQ 而不是循环。

对于总和:

decimal total = salesList.Sum()

平均而言:

decimal avg = salesList.Average();