使用string.Format

时间:2018-10-29 00:56:00

标签: c# console

每次我尝试输入销售数量。运行此方法时,输入字符串的格式不正确。

int numberOfSales = 0;
double[] sales;
Console.Write("Please enter number of sales: ");
numberOfSales = Convert.ToInt32(Console.ReadLine());
sales = new double[numberOfSales];

for (int i = 0; i < numberOfSales; i++)
{

   Console.Write("Please enter  sales #{0}:", i + 1);

   sales[i] = Convert.ToDouble(Console.ReadLine());
}

double sum = sales.Sum();

for (int i = 0; i < numberOfSales; i++)
{

   double contrubution = sales[i] / sum;

   Console.WriteLine("Sale # {0} was {1:C2} and contributed {2P:P2}", i + 1, sales[i], contrubution);
}

Console.WriteLine("Total sum of sales is {0:C2}", sum);

enter image description here

1 个答案:

答案 0 :(得分:2)

您的问题出在(但不限于)2P

背景

string.Format中的花括号表示格式项。它们由令牌 Number 表示,后跟可选的:Format Specifier

令牌 Number {0}是对象的 Index ,其字符串值将插入该位置。

解决方案

正如您在代码中看到的那样,您有{2P:P2},其开头不是项目编号格式。应该是{2:P2}

Console.WriteLine("Sale # {0} was {1:C2} and contributed {2:P2}", i + 1, sales[i], contrubution);

其他

我可以建议使用C#6中引入的string interpolation,它更易于阅读,并且不太可能出现这样的错误

Console.WriteLine($"Sale # {(i + 1)} was {sales[i]:C2} and contributed {contrubution:P2}");