[英]Display the sum of digits in a number entered by the user
I need to get a number from the user and display the sum of that number's digits. 我需要从用户那里得到一个数字,并显示该数字的总和。 For example, the sum of the digits in the number
12329
is 17
. 例如,数字
12329
中的数字12329
为17
。
Here's what I tried to do and it is giving me the ASCII code instead: 这是我尝试做的,而是给了我ASCII码:
Console.WriteLine("please enter a number: ");
string num = Console.ReadLine();
int len = num.Length;
int[] nums = new int[len];
int sum = 0;
int count = 0;
while (count < len)
{
nums[count] = Convert.ToInt32(num[count]);
count++;
}
for (int i = 0; i < len; i++)
sum += nums[i];
Console.WriteLine(sum);
This is a very common mistake. 这是一个非常常见的错误。
char
is really just a number - the encoding value of the character represented by the char
. char
实际上只是一个数字-char表示的char
的编码值。 When you do Convert.ToInt32
on it, it sees the char
as a number and says "alright let's just convert this number to 32 bits and return!" 当您对它执行
Convert.ToInt32
时,它会将char
视为一个数字,并说:“好吧,我们将这个数字转换为32位并返回!” instead of trying to parse the character. 而不是尝试解析字符。
"Wait, where have I used a char
in my code?" “等等,我在代码中的哪里使用了
char
?” you might ask. 你可能会问。 Well, here:
好吧,在这里:
Convert.ToInt32(num[count]) // 'num[count]' evaluates to 'char'
To fix this, you need to convert the char
to a string
: 要解决此问题,您需要将
char
转换为string
:
nums[count] = Convert.ToInt32(num[count].ToString());
^^^^^^^^^^^^^^^^^^^^^
Now you are calling a different overload of the ToInt32
method, which actually tries to parse the string. 现在,您正在调用
ToInt32
方法的另一个重载,该方法实际上尝试解析该字符串。
When you access your string with a index (in your case num[count]
) you get a char type and because of that you are getting ASCII values. 当您使用索引(在您的情况下为
num[count]
)访问字符串时,将获得一个char类型,因此将获得ASCII值。 You can convert char to string with .ToString()
in your case nums[count] = Convert.ToInt32(num[count].ToString());
您可以在情况下使用
.ToString()
将char转换为字符串nums[count] = Convert.ToInt32(num[count].ToString());
.I posted here another approach to your problem: 我在这里发布了另一种解决您问题的方法:
string number = Console.ReadLine();
int sum = 0;
foreach (var item in number)
{
sum += Convert.ToInt32(item.ToString());
}
Console.WriteLine(sum);
As you noticed the Convert.ToInt32(num[count])
will only return the Unicode code of the char
you want to convert, because when you use the []
operator on a string
, you will get readonly access to [the] individual characters of a string [1] . 正如您所注意到的,
Convert.ToInt32(num[count])
将仅返回要转换的char
的Unicode代码,因为当您在string
上使用[]
运算符时,您将获得对[the]个单个字符的只读访问权限字符串 [1] 。
And so you are using Convert.ToInt32(Char)
, which 因此,您正在使用
Convert.ToInt32(Char)
,其中
Converts the value of the specified Unicode character to the equivalent 32-bit signed integer.
将指定的Unicode字符的值转换为等效的32位带符号整数。
One way to cast the numeric value from a char
to a digit, is using Char.GetNumericValue()
, which 将数字值从
char
转换为数字的一种方法是使用Char.GetNumericValue()
,该方法
Converts a specified numeric Unicode character to a double-precision floating-point number.
将指定的数字Unicode字符转换为双精度浮点数。
By using System.Linq;
通过
using System.Linq;
you can cut your code to just a few lines of code. 您可以将代码缩减为几行代码。
Console.WriteLine("please enter a number: ");
string num = Console.ReadLine(); // "12329"
int sum = (int)num.Select(n => Char.GetNumericValue(n)).Sum();
Console.WriteLine(sum); // 17
What does this line of code? 这行代码是什么?
The num.Select(n => Char.GetNumericValue(n))
will iterate over each char in your string, like your while
and converts each value to a double
value and return an IEnumerable<double>
. num.Select(n => Char.GetNumericValue(n))
将遍历字符串中的每个char,就像您的while
,并将每个值转换为double
值并返回IEnumerable<double>
。 The Sum()
itself will iterate over each value of the IEnumerable<double>
and calculate the sum as a double
. Sum()
本身将迭代IEnumerable<double>
每个值,并将总和计算为double
。 And since you want an integer as result the (int)
casts the double
into an integer value. 并且由于要使用整数作为结果,因此
(int)
将double
精度转换为整数值。
Side-Note: 边注:
You could check your input, if it is really an integer. 如果确实是整数,则可以检查您的输入。 For example:
例如:
int intValue;
if(Int32.TryParse(num, out intValue))
{
// run the linq
}
else
{
// re-prompt, exit, ...
}
If you are using Char.GetNumericValue()
on an letter it will return -1
so for example the sum of string num = "123a29";
如果您在一个字母上使用
Char.GetNumericValue()
,它将返回-1
,例如, string num = "123a29";
的总和string num = "123a29";
will be 16
. 将
16
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.