更新时间:2022-11-09 10:24:03
for (int i = 0; i < parts.Length; i++)
{
Console.WriteLine("{0, 5}", parts[i]);
sum += Convert.ToInt32(parts[i]);
}
已固定。
您试图将 1 2 3 4 5 55转换为 int
。您必须将 1, 2, 3 ...转换为 int
并将它们添加到 sum
。
You were trying to convert "1 2 3 4 5 55" to an int
. You must convert "1", "2, "3"... to an int
and add them to sum
.
我要补充一点,如果您想分割字符串,***做类似
I'll add that if you want to Split the string, it would be better to do something like
string[] parts = list.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
通过这种方式,数字之间的多个空格将被删除(例如1 2 3)
In this way multiple spaces between numbers are removed (1 2 3 for example)
Andrei发布了一个使用LINQ的非常简单的示例...
Andrei had posted a very simple example of use of LINQ...
int sum = parts.Sum(p => Convert.ToInt32(p));
这会超出 for
周期。它将转换为 int
并添加所有部分。这意味着对于每个部分
将其转换为 int
并添加。返回总和。
This you would put OUTSIDE the for
cycle. It converts to int
and adds all the "parts". It means "for each part
convert it to int
and add it. Return the sum".