简体   繁体   中英

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 .

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);

This is a very common mistake. char is really just a number - the encoding value of the character represented by the 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!" instead of trying to parse the character.

"Wait, where have I used a char in my code?" 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 :

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.

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);

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM