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

标签 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();

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

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

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

我是 C# 的新手,因此非常感谢任何帮助。谢谢!

最佳答案

当您在字符串上使用索引器时:example[example.Length - 1] 您将返回一个值为 '3'char >(不是字符串 "3")。

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

char : Converts the value of the specified Unicode character to the equivalent 32-bit signed integer.

相对于

string: Converts the specified string representation of a number to an equivalent 32-bit signed integer.

如果你拿 peek at a Unicode table ,您会看到 '3' 的值为十六进制 33,即 51。

使用 example[example.Length - 1].ToString() 可能会更好。

关于C# 的 Convert.ToInt32(3) 转换为 51,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42405149/

相关文章:

c# - 设置 ASP.NET Button 属性客户端和读取属性值服务器端

c# - 如何显示另一个UI线程上的对话框

c# - 从 MVC 3 中的 ActionResult 类型方法将 JSon 数组返回到 $.ajax

c# - 关于通用类的Unity 2.0 IOC配置

c# - 对从 Linq2Sql 的 var 中获取 int 感到困惑

c# - 如何确定在 C# 中发送电子邮件的时区

c# - 从下拉 Angular 中删除选定值

c# - 对缓冲的 Observable 进行排序

c# - 使用相等运算符比较两个 floored double 是否安全?

c# - 使用 COM+ 在 MSXML 和 .Net 之间互操作