简体   繁体   English

从将字符转换为 integer 获取不同的值

[英]Getting different values from convert char to integer

when I display the 'i' variable, which would be a char value当我显示 'i' 变量时,这将是一个 char 值

{
  class Program {
    static void Main(string[] args) {
      var max = 0;
      var lista = new char[] {
        '1',
        '2',
        '3',
        '4'
      };
      foreach(char i in lista) {
        Console.WriteLine(i);
        /* var hola =  Convert.ToInt32(i);
          Console.WriteLine(hola);*/
      }
    }
  }
}

I get this:我明白了:

> 1 2 3 4

However, when converting 'i' into an int但是,当将 'i' 转换为 int

var max = 0;
var lista = new char[] {
  '1',
  '2',
  '3',
  '4'
};
foreach(char i in lista) {
  var hola = Convert.ToInt32(i);
  Console.WriteLine(hola);
}    
            

I get this:我明白了:

49 50 51 52 49 50 51 52

Any idea what could be the problem?知道可能是什么问题吗? I'd like to obtain the same values, so I can evaluate them as integers and obtain the biggest of them, but I can't.我想获得相同的值,所以我可以将它们评估为整数并获得其中最大的值,但我不能。

When you convert a char to an int , you get the ASCII value of that character.当您将char转换为int时,您将获得该字符的 ASCII 值。 The neat thing with these values is that they are sequential, so if you subtract the value of '0' (the 0 character ), you can convert a character representing a digit to that digit:这些值的巧妙之处在于它们是连续的,因此如果减去'0'的值(0字符),您可以将表示数字的字符转换为该数字:

var hola =  i - '0';

If you want the literal character and not the ascii number of the character, use the ToString() method如果您想要文字字符而不是字符的 ascii 编号,请使用ToString()方法

var hola =  Convert.ToInt32(i.ToString());

WriteLine method internally converts the parameters string. WriteLine 方法在内部转换参数字符串。 Thus you can have the value you want.因此,您可以拥有您想要的价值。 ToInt method return the ASCII value of that char. ToInt 方法返回该字符的 ASCII 值。 You have to convert your i value to string i.ToString() or you can simply substract 48 from the converted value.您必须将您的 i 值转换为字符串i.ToString()或者您可以简单地从转换后的值中减去 48。

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

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