So for practice, I decided to attempt to create a C# program, that calculates the sum of the individual digits of a given (eg If I were to input the number 123, the sum should be 6, because 1 + 2 + 3..)
My thought process is that I would use a for loop to iterate through a specific number (I'd have to convert the number first to a string though), add each individual number into a list, and then find the sum of that list, in order to get my answer. However, when I do so, as demonstrated by the code below:
static void Main(string[] args)
{
int num;
int sumOfNum = 0;
List<int> numbersToAdd = new List<int>();
Console.WriteLine("insert number: ");
num = Convert.ToInt32(Console.ReadLine());
string myNum = num.ToString();
for (int i = 0; i < myNum.Length; i++)
{
numbersToAdd.Add(myNum[i]);
}
foreach (int n in numbersToAdd)
{
sumOfNum = numbersToAdd.Sum();
}
Console.WriteLine("the sum is " + sumOfNum);
}
Instead of the output is 6, my output instead is 150. I thought it was weird, so when I decided to iterate through my list, so I can see my values, as shown below:
foreach (int n in numbersToAdd)
{
Console.WriteLine(n);
}
Instead of getting the values 1, 2, and 3, I instead get 49, 50, 51.
Why is that? Is it because of the fact that I'm sending in an index of a string, instead of an actual int? And if so, how can I fix it?
myNum
is a string, this means that myNum[i]
will return a character and not an int
. However, the char
is implicitly converted to an int
in your case, but you still get the ASCII-value of the character.
In your case, these characters happen to be '1'
, '2'
and '3'
, which have an ASCII-value of 49, 50 and 51 respectively. To see other ASCII values, search the Internet for 'ASCII table'.
To fix your code, you must convert those ASCII-values back to their decimal value by subtracting the value of the '0'
-character:
numbersToAdd.Add(myNum[i] - '0');
Apart from that, you don't have to convert the number to a string, you can use modulus 10 to get the right-most digit: num % 10
and then divide num
with 10 to advance to the next digit: num /= 10;
. Do this in a loop for as long num
differs from zero.
while (num > 0)
{
sumOfNum += num % 10;
num /= 10;
}
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.