C# 使用string.Format时发生FormatException错误

C# 使用string.Format时发生FormatException错误,c#,console,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++

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

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);
int numberOfSales=0;
双[]销售额;
控制台。写入(“请输入销售数量:”);
numberOfSales=Convert.ToInt32(Console.ReadLine());
销售=新的双[销售数量];
对于(int i=0;i
您的问题在于(可能不限于)
2P

背景

字符串中的大括号。Format
表示格式项。它们由一个令牌号表示,后跟可选的

令牌编号
{0}
是将在该位置插入其字符串值的对象的索引

解决方案

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

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

我可以建议在
C#6
中引入哪个选项吗?相反,它更容易阅读,也不太可能犯这样的错误

Console.WriteLine($"Sale # {(i + 1)} was {sales[i]:C2} and contributed {contrubution:P2}");
您的问题在于(可能不限于)
2P

背景

字符串中的大括号。Format
表示格式项。它们由一个令牌号表示,后跟可选的

令牌编号
{0}
是将在该位置插入其字符串值的对象的索引

解决方案

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

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

我可以建议在
C#6
中引入哪个选项吗?相反,它更容易阅读,也不太可能犯这样的错误

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