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
.
Here's what I tried to do and it is giving me the ASCII code instead:
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);
答案 0 :(得分:2)
这是一个非常常见的错误。 char
实际上只是一个数字 - char
所代表的字符的编码值。当您对其Convert.ToInt32
进行操作时,它会将char
视为一个数字并说出&#34;好吧,我们只需将此数字转换为32位并返回!&#34;而不是试图解析角色。
&#34;等等,我的代码在哪里使用过char
?&#34;你可能会问。好吧,这里:
Convert.ToInt32(num[count]) // 'num[count]' evaluates to 'char'
要解决此问题,您需要将char
转换为string
:
nums[count] = Convert.ToInt32(num[count].ToString());
^^^^^^^^^^^^^^^^^^^^^
现在,您正在调用ToInt32
方法的不同重载,该方法实际上会尝试解析字符串。
答案 1 :(得分:1)
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. You can convert char to string with .ToString()
in your case 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);
答案 2 :(得分:0)
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].
And so you are using Convert.ToInt32(Char)
, which
Converts the value of the specified Unicode character to the equivalent 32-bit signed integer.
One way to cast the numeric value from a char
to a digit, is using Char.GetNumericValue()
, which
Converts a specified numeric Unicode character to a double-precision floating-point number.
By 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>
. The Sum()
itself will iterate over each value of the IEnumerable<double>
and calculate the sum as a double
. And since you want an integer as result the (int)
casts the double
into an integer value.
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";
will be 16
.