首页 > 解决方案 > 将 char 数字转换为 int 时的值不正确

问题描述

我的最终目标是取一个像 29 这样的数字,将其分开,然后将所得的两个整数相加。因此,例如,如果数字是 29,则答案将是 2 + 9 = 11。

当我调试时,我可以看到这些值被保留,但在这种情况下,其他值似乎也不正确 50、57。所以,我的答案是 107。我不知道这些值来自哪里我不知道从哪里开始修复它。

我的代码是:

class Program
{
    static void Main(string[] args)
    {
        int a = 29;
        int answer = addTwoDigits(a);
        Console.ReadLine();


    }
        public static int addTwoDigits(int n)
        {
            string number = n.ToString();
            char[] a = number.ToCharArray();
            int total = 0;

            for (int i = 0; i < a.Length; i++)
            {
                total = total + a[i];
            }
            return total;
        }

}

标签: c#

解决方案


如前所述,您的代码问题是,当您转换为int与各种数字不匹配的字符时,字符具有 ASCII 代码值。不要搞乱字符串和字符,而是使用好的旧数学。

public static int AddDigits(int n)
{
    int total = 0;
    while(n>0)
    {
        total += n % 10;
        n /= 10;
    }

    return total;
}

以 10 为模将产生最低有效位,因为整数除法截断n /= 10将截断最低有效位,并在您用完数字时最终变为 0。


推荐阅读