简体   繁体   English

将char位数转换为int时,值不正确

[英]Incorrect values when converting char digits to int

My end goal is to take a number like 29, pull it apart and then add the two integers that result. 我的最终目标是取一个像29的数字,将其拆开,然后将得到的两个整数相加。 So, if the number is 29, for example, the answer would be 2 + 9 = 11. 因此,例如,如果数字是29,则答案将是2 + 9 = 11。

When I'm debugging, I can see that those values are being held, but it appears that other values are also being incorrect in this case 50, 57. So, my answer is 107. I have no idea where these values are coming from and I don't know where to begin to fix it. 在调试时,我可以看到保留了这些值,但是在这种情况下,其他值似乎也不正确,即50、57。因此,我的答案是107。我不知道这些值从何而来而且我不知道从哪里开始修复它。

My code is: 我的代码是:

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

}

As mentioned the issue with your code is that characters have a ASCII code value when you cast to int which doesn't match with the various numerical digits. 如前所述,代码的问题在于,当您将字符转换为int时,字符具有ASCII码值,该值与各种数字都不匹配。 Instead of messing with strings and characters just use good old math instead. 不用弄乱字符串和字符,只需使用良好的旧数学即可。

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

    return total;
}

Modulo by 10 will result in the least significant digit and because integer division truncates n /= 10 will truncate the least significant digit and eventually become 0 when you run out of digits. 乘以10的模将导致最低有效数字,并且由于整数除法将n /= 10截断n /= 10将截断最低有效数字并最终在数字用尽时变为0。

Your code is actually additioning the decimal value of the char. 您的代码实际上是将char的十进制值相加。
Take a look at https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html 看看https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html

Decimal value of 2 and 9 are 50 and 57 respectively. 小数2和9分别为50和57。 You need to convert the char into a int before doing your addition. 在进行加法之前,需要将char转换为int。

int val = (int)Char.GetNumericValue(a[i]);

Your problem is that you're adding char values. 您的问题是您要添加char值。 Remember that the char is an integer value that represents a character in ASCII. 请记住,char是一个整数值,代表ASCII字符。 When you are adding a[i] to total value, you're adding the int value that represents that char , the compiler automatic cast it. 当你加入a[i] ,以total价值,你要添加的int表示该值char ,编译器自动将其丢。

The problem is in this code line: 问题在以下代码行中:

total = total + a[i];

The code above is equal to this code line: 上面的代码等于以下代码行:

total += (int)a[i];

// If a[i] = '2', the character value of the ASCII table is 50.
// Then, (int)a[i] = 50.

To solve your problem, you must change that line by this: 要解决您的问题,您必须通过以下方式更改该行:

total = (int)Char.GetNumericValue(a[i]);

// If a[i] = '2'.
// Then, (int)Char.GetNumericValue(int)a[i] = 2.

You can see this answer to see how to convert a numeric value from char to int . 您可以看到此答案,以了解如何将数字值从char转换为int

At this page you can see the ASCII table of values. 在此页面上,您可以看到ASCII值表。

Just for fun, I thought I'd see if I could do it in one line using LINQ and here it is: 只是为了好玩,我想我可以看看是否可以使用LINQ在一行中完成它,这里是:

public static int AddWithLinq(int n)
{
    return n.ToString().Aggregate(0, (total, c) => total + int.Parse(c.ToString()));
}

I don't think it would be particularly "clean" code, but it may be educational at best! 我认为这不是特别“干净”的代码,但充其量是很有教育意义的!

Try this: 尝试这个:

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 + (int)Char.GetNumericValue(a[i]);
        }
        return total;
    }

Converted number to char always returns ASCII code.. So you can use GetNumericValue() method for getting value instead of ASCII code 将数字转换为char始终返回ASCII代码。因此,您可以使用GetNumericValue()方法获取值而不是ASCII代码

You should you int.TryParse 你应该int.TryParse

  int num; 
 if (int.TryParse(a[i].ToString(), out num))
  {
      total += num; 
   }
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 +=  Convert.ToInt32(number[i].ToString());
    }
    return total;
}

You don't need to convert the number to a string to find the digits. 您无需将数字转换为字符串即可找到数字。 @juharr already explained how you can calculate the digits and the total in a loop. @juharr已经解释了如何在循环中计算数字和总数。 The following is a recursive version : 以下是递归版本:

int addDigit(int total,int n)
{
    return (n<10) ? total + n
                  : addDigit(total += n % 10,n /= 10);
}

Which can be called with addDigit(0,234233433) and returns 27. If n is less than 10, we are counting the last digit. 可以使用addDigit(0,234233433)调用并返回27。如果n小于10,我们将计算最后一位。 Otherwise extract the digit and add it to the total then divide by 10 and repeat. 否则,提取数字并将其添加到总数中,然后除以10并重复。

One could get clever and use currying to get rid of the initial total : 一个人可能会变得聪明,并使用currying摆脱最初的总数:

int addDigits(int i)=>addDigit(0,i);

addDigits(234233433) also returns 27; addDigits(234233433)还返回27;

If the number is already a string, one could take advantage of the fact that a string can be treated as a Char array, and chars can be converted to ints implicitly : 如果数字已经是一个字符串,则可以利用以下事实:可以将字符串视为Char数组,并且可以将char隐式转换为ints:

var total = "234233433".Sum(c=>c-'0');

This can handle arbitrarily large strings, as long as the total doesn't exceed int.MaxValue , eg: 只要总数不超过int.MaxValue ,就可以处理任意大的字符串,例如:

"99999999999999999999".Sum(x=>x-'0');  // 20 9s returns 180

Unless the number is already in string form though, this isn't efficient nor does it verify that the contents are an actual number. 除非数字已经是字符串形式,否则这将是无效的,也不会验证内容是否为实际数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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