当创建一个接受数字(如 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/