2

我是这个网站的新手,对编程也很陌生,目前我正在尝试在我的捐赠列表上显示用户名的计数,然后我还想要一个总和来计算总金额捐赠清单包含的钱,如果有人可以帮助我创建一种方法来在donations.txt文件中添加捐赠者的数量,这将是非常有帮助的,我不知道从哪里开始,但到目前为止这是我的编码:

        string sName;
        double dAmount;
        string sTotalNames;
        double dAmountTotal;
        double dAmountAverage;

    using (StreamReader sr = new StreamReader("Donations.txt"))
    {
        while (sr.Peek() != -1)
        {
            sName = sr.ReadLine();
            Console.WriteLine(sName);

            dAmount = Convert.ToDouble(sr.ReadLine());
            Console.WriteLine(dAmount);
        }

        Console.WriteLine("Press any key to close");
        Console.ReadKey();
    }
4

3 回答 3

3

假设您拥有的所有其他东西都正常工作,那么创建一个总和将非常容易。

string sName;
double dAmount;
int sTotalNames = 0;
double dAmountTotal = 0;
double dAmountAverage;

using (StreamReader sr = new StreamReader("Donations.txt"))
{
    while (sr.Peek() != -1)
    {
        sName = sr.ReadLine();
        Console.WriteLine(sName);

        dAmount = Convert.ToDouble(sr.ReadLine());
        Console.WriteLine(dAmount);
        dAmountTotal += dAmount;
        sTotalNames++;
    }
    dAmountAverage = dAmountTotal / sTotalNames;
    Console.WriteLine("Sum = {0}", dAmountTotal );
    Console.WriteLine("Total Names = {0}", sTotalNames);
    Console.WriteLine("Average Amount = {0}", dAmountAverage);
    Console.WriteLine("Press any key to close");
    Console.ReadKey();
}
于 2013-11-13T03:51:47.257 回答
1
List<double> dAmountList = new List<double>();

using (StreamReader sr = new StreamReader("Donations.txt"))
{
    while (sr.Peek() != -1)
    {
        sName = sr.ReadLine();
        Console.WriteLine(sName);

        dAmount = Convert.ToDouble(sr.ReadLine());
        Console.WriteLine(dAmount);
        dAmountList.Add(dAmount);

    }

    double sum = dAmountList.Sum(); //here you have your sum

    int dAmountOfDonators = dAmountList.Count(); //here you have your donators total count

    Console.WriteLine("Press any key to close");
    Console.ReadKey();
}
于 2013-11-13T03:51:32.480 回答
1

快速紧凑的实现:

var lines = File.ReadAllLines("Donations.txt");

// Convert odd rows to Double
var amounts = lines.Where((x,i) => i % 2 == 1)
                   .Select(Convert.ToDouble)
                   .ToArray();

var sum = amounts.Sum();
var count = amounts.Count();
于 2013-11-13T04:18:52.163 回答