C# I';如果打印了字符串的Ascii字符,如何将这些值相加?
所以我得到了这个:C# I';如果打印了字符串的Ascii字符,如何将这些值相加?,c#,.net,C#,.net,所以我得到了这个: string name = ""; int sum = 0; Console.WriteLine("What's you name?"); name = Console.ReadLine(); foreach (char c in name) { Console.WriteLine((int)c); } sum = Console.ReadKey(); 现在我的问题是,如何添加所有字符的ASCII码的值?这相当简单 string name = ""; int sum
string name = "";
int sum = 0;
Console.WriteLine("What's you name?");
name = Console.ReadLine();
foreach (char c in name)
{
Console.WriteLine((int)c);
}
sum = Console.ReadKey();
现在我的问题是,如何添加所有字符的ASCII码的值?这相当简单
string name = "";
int sum = 0;
Console.WriteLine("What's you name?");
name = Console.ReadLine();
foreach (char c in name)
{
Console.WriteLine((int)c);
sum += (int) c; // This line will add all the values together
}
Console.WriteLine(sum.ToString()); // If you want to print to the console the sum.
// sum = // This line will prevent compilation. Does it need removing?
Console.ReadKey();
归功于@George Alexandria
可能值得使用GetNumericValue函数,而不是强制转换。
例如:
(int)Char.GetNumericValue(c);
sum+=(int)c;控制台写入线((int)c)代码>在foreach@Oliver,我希望您在foreach@faheemkhan,是的,我知道,但出于某种原因,我添加了Console.WriteLine((int)c)代码>再次。