我需要有关如何使程序显示最终所有定价的平均值的帮助
static void Main(string[] args)
{
int[] hours = new int[31];
const decimal HOURLY_RATE = 2.5M;
const decimal MAX_FEE = 20.00M;
decimal pay;
int counter = 0;
string line;
StreamReader fileSR = new StreamReader("hours.txt");
line = fileSR.ReadLine();
while (line != null)
{
hours[counter] = int.Parse(line);
counter = counter + 1;
line = fileSR.ReadLine();
}
fileSR.Close();
Console.WriteLine("hours pay");
for (int i = 0; i < hours.Length; i++)
{
pay = Math.Min(hours[i] * HOURLY_RATE, MAX_FEE);
Console.WriteLine("{0,4} {1,10}", hours[i], pay.ToString("C"));
}
Console.ReadKey();
}
} }
我有点坚持如何让它显示所有结果然后在应用程序底部添加平均值
答案 0 :(得分:0)
我更喜欢使用类似下面的类来处理文件中的所有数据:
public class wages
{
const decimal HOURLY_RATE = 2.5M;
const decimal MAX_FEE = 20.00M;
private int _WorkingHour;
public int WorkingHour
{
get { return _WorkingHour; }
set
{
_WorkingHour = value;
_AmountToPay = Math.Min(value * HOURLY_RATE, MAX_FEE);
}
}
private decimal _AmountToPay;
public decimal AmountToPay
{
get { return _AmountToPay; }
}
public override string ToString()
{
return String.Format("{0,4} {1,10}", WorkingHour, AmountToPay.ToString("C"));
}
}
然后创建一个类列表来存储文件中的详细信息,显示它们并计算总和和平均值,如下所示:
var LinesInFile = System.IO.File.ReadAllLines("hours.txt");
List<wages> wagesList = new List<wages>();
foreach (string line in LinesInFile)
{
wagesList.Add(new wages() { WorkingHour = int.Parse(line) });
}
// Display the details
Console.WriteLine("hours pay");
foreach (wages wage in wagesList)
{
Console.WriteLine(wage.ToString());// overrided method will give you the formated string
}
Console.WriteLine("Average Pay : {0}", wagesList.Average(x => x.AmountToPay));
如果您仍然想要使用您的代码,那么您必须声明一个变量以保持薪酬总和,然后根据该值获得平均值,我认为您必须遵循以下代码:
Console.WriteLine("hours pay");
decimal sumOfPay = 0;
for (int i = 0; i < hours.Length; i++)
{
pay = Math.Min(hours[i] * HOURLY_RATE, MAX_FEE);
sumOfPay += pay;
Console.WriteLine("{0,4} {1,10}", hours[i], pay.ToString("C"));
}
Console.WriteLine("Average Pay : {0}", sumOfPay / hours.Length );