此代码的目标是将整数中的所有整数添加到一个值中(例如"2013" => 6
(,在c#中,我编写了代码,因此它一次一个地将数字输出到相应的ASCII值,但我不知道如何将其转换回数值。
注意,我是C#的新手
string Year;
int Total = 0;
int Adding = 0;
int Adding2 = 0;
Console.WriteLine("Write The year you want converted");
Year = Console.ReadLine();
for (int i = 0; i < Year.Length; i++)
{
Adding2 = Year[i];
Adding = Convert.ToInt32(Adding2);
Total = Adding + Total;
Console.WriteLine(Total);
}
您应该求和值,而不是ascii码:
...
for (int i = 0; i < Year.Length; i++)
{
Adding2 = Year[i];
Adding = Adding2 - '0';
Total = Adding + Total;
}
Console.WriteLine(Total);
在一般情况中,可以使用char。GetNumericValue((:
// double: some characters have fractional values: '⅝'
double Total = 0.0;
foreach (char c in Year) {
double value = char.GetNumericValue(c);
// If character has value (e.g. 'A' doesn't have)
if (value != -1)
Total += value;
}
Console.WriteLine(Total);