0

这是 "C:\grades" 的比赛:

Khaled
80
90
70
Ammar
100
99
100
Wael
43
56
79

这是我使用的代码:

StreamReader sr = new StreamReader("C:\\grades.txt");
StreamWriter sw = new StreamWriter("C:\\ava.txt");
string line;
float sum=0;
float avg=0;

while ((line = sr.ReadLine()) != null)
{
    if ((line[0] >= 65 && line[0] <= 90) || (line[0] >= 97 && line[0] <= 122))
    {
        avg = sum / 3;
        if (avg != 0)
            sw.WriteLine(avg.ToString());
        sum = 0;
        avg = 0;
        sw.WriteLine(line);
    }
    else
    {
        sw.WriteLine(line);
        sum += float.Parse(line);
    }
}

此代码是创建一个文本文件,如下所示:

Khaled
80
90
70
80
Ammar
100
99
100
99.66
Wael
43
56
79
59.33

其中添加的数字是平均值。

4

2 回答 2

2

您需要正确处理写入器,否则它不会刷新输出。

string line;
float sum=0;
float avg=0;

using(StreamReader sr = new StreamReader("C:\\grades.txt"))
using(StreamWriter sw = new StreamWriter("C:\\ava.txt"))
{
    while ((line = sr.ReadLine()) != null)
    {
        if ((line[0] >= 65 && line[0] <= 90) || (line[0] >= 97 && line[0] <= 122))
        {
            avg = sum / 3;
            if (avg != 0)
                sw.WriteLine(avg.ToString());
            sum = 0;
            avg = 0;
            sw.WriteLine(line);
        }
        else
        {
            sw.WriteLine(line);
            sum += float.Parse(line);
        }
    }
}
于 2013-04-19T11:58:51.570 回答
0

也许这可以简化您的任务。它显示了如何将字符串解析为数字(我已经使用过Decimal),用于Enumerable.Average获取平均值并Math.Round对其进行舍入:

var userGrades = new Dictionary<string, List<decimal>>();
string currentUserName = null;
foreach (string line in File.ReadLines(sourcePath))
{ 
    decimal grade;
    if (decimal.TryParse(line.Trim(), out grade))
    {
        // line with a grade
        List<decimal> grades;
        userGrades.TryGetValue(currentUserName, out grades);
        if (grades != null) grades.Add(grade);
    }
    else
    {
        // line with the name
        currentUserName = line.Trim();
        if (!userGrades.ContainsKey(currentUserName))
            userGrades.Add(currentUserName, new List<decimal>());
    }
}

using (var writer = new StreamWriter(destPath))
{
    foreach (var ug in userGrades)
    {
        writer.WriteLine(ug.Key);
        foreach(decimal d in ug.Value)
            writer.WriteLine(d);
        decimal roundedAverage = Math.Round(ug.Value.Average(), 2);
        writer.WriteLine(roundedAverage);
    }
}

请注意,using周围的StreamWriter确保它被关闭/处理也将它的输出刷新到文件中。我假设你错过了这个。

于 2013-04-19T12:17:01.970 回答