internal class Invoice
{
public static decimal[] Total =
{
InvoiceLineItem.quantity[0] * InvoiceLineItem.pricePerUnit[0],
InvoiceLineItem.quantity[1] * InvoiceLineItem.pricePerUnit[1],
InvoiceLineItem.quantity[2] * InvoiceLineItem.pricePerUnit[2],
InvoiceLineItem.quantity[3] * InvoiceLineItem.pricePerUnit[3],
InvoiceLineItem.quantity[4] * InvoiceLineItem.pricePerUnit[4],
InvoiceLineItem.quantity[5] * InvoiceLineItem.pricePerUnit[5],
};
private decimal total1;
private decimal total2;
public void Customer1()
{
for (var i = 0; i < 3; i++)
Console.WriteLine(String.Format("{0,-15} {1,-20} {2,-15} {3,-15} {4,-10}",
InvoiceLineItem.productNumber[i],
InvoiceLineItem.description[i],
InvoiceLineItem.quantity[i],
InvoiceLineItem.pricePerUnit[i],
InvoiceLineItem.Total[i]));
}
public void Customer2()
{
for (var k = 3; k <= 5; k++)
{
Console.WriteLine(String.Format("{0,-15} {1,-20} {2,-15} {3,-15:C} {4,-10:C}",
InvoiceLineItem.productNumber[k],
InvoiceLineItem.description[k],
InvoiceLineItem.quantity[k],
InvoiceLineItem.pricePerUnit[k],
Total[k]));
}
}
public void Customer1Total()
{
for (var i = 0; i <= 2; i++)
{
total1 += Total[i];
Console.WriteLine(String.Format("\nTotal of Customer 1:{0:C}", total1));
}
}
}
我很难在方法Customer1Total()
中打印一次for循环。我需要输出total1
只打印一次,但它会打印3次,逐步添加总计。基本上我只需要这个for循环的最后结果,但我看到了所有的增量。另外,对于额外的信息,我在我的主要方法中调用方法customer1total
进行打印。
谢谢。
答案 0 :(得分:1)
public void Customer1Total()
{
for(int i = 0; i <= 2; i++)
{
total1 += Invoice.Total[i];
}
//Move write line outside the loop
Console.WriteLine(String.Format("\nTotal of Customer 1:{0:C}", total1));
}
答案 1 :(得分:0)
您的Console.WriteLine
语句位于循环体内,之后将其移动以使其在循环结束后执行:
for(int i = 0; i <= 2; i++)
{
total1 += Invoice.Total[i];
}
Console.WriteLine(String.Format("\nTotal of Customer 1:{0:C}", total1));
另外,请注意,因为total1
是类级变量,所以它的值将在调用Customer1Total()
之间保持不变,导致每次调用函数时它都会增加。