C#的Convert.ToInt32(3)转换为51

Mua*_*eim 2 c#

当创建一个带有数字的程序(如1253)并将其转换为125 ^ 3时,我得到一个奇怪的错误,转换字符串似乎不起作用.这是我的代码:

        string example = "1253";

        // grab all but the last character
        int num = Convert.ToInt32(example.Substring(0, example.Length - 1));
        Console.WriteLine(num);

        // grab the last character
        //int pow = Convert.ToInt32(example.Substring(example.Length - 1));
        int pow = Convert.ToInt32(example[example.Length - 1]);
        Console.WriteLine(pow);

        // output num to the power of pow
        Console.WriteLine(Math.Pow(num, pow));
        Console.ReadKey();
Run Code Online (Sandbox Code Playgroud)

变量pow的第一次初始化正常工作,但第二次(未注释掉)不是出于某种原因.抓取字符串的最后一个字符的不同方法有效,但由于某种原因,第一个"3"将转换为3,但对于后者"3"将转换为51.

这是使用pow的注释初始化时的输出:
125
3
1953125

这是使用pow的未注释初始化时的输出:
125
51
8.75811540203011E + 106

我对C#很新,所以任何帮助都会非常感激.谢谢!

spe*_*der 9

在字符串上使用索引器时:example[example.Length - 1]返回char'3'(不是字符串"3").

这意味着Convert.ToInt32使用a char作为参数调用不同的重载.应用于a的转换与应用于a的转换char完全不同string.

char:将指定的Unicode字符的值转换为等效的32位有符号整数.

而不是

string:将指定的数字字符串表示形式转换为等效的32位有符号整数.

如果你看一下Unicode表,你会看到它'3'的值为十六进制33或51.

你可能会有更好的运气example[example.Length - 1].ToString().