此程序:
static void Main(string[] args)
{
int x;
Console.Write("Enter number:");
x = Convert.ToInt32(Console.Read());
Console.WriteLine($"Output: {x}");
}
控制台文本:
Enter number: 5
Output: 53
Press any key to continue...
截屏:
输入数字5但输出不是5
Console.Read()
读取单个字符作为char
,而不是整行作为string
。char
]值本身实际上是整数,对于大多数操作,C#/。NET不会将其处理为文本,这可能会淘汰初学者。'5'
的整数值(作为char
)is 53 in ASCII and Unicode。Convert.ToInt32(Char)
将char
值视为整数(因此'5'
为53
),然后将其转换为Int32
值,而不是将字符解析为十进制数字。Convert
类。 .NET Framework中有更好的替代方法(例如Int32.TryParse
)。要解决此问题,请使用Console.ReadLine()
和Int32.TryParse
而不是Convert.ToInt32
,以便可以正常处理无效输入。
while( true )
{
Console.Write( "Enter number: " );
String input = Console.ReadLine();
if( Int32.TryParse( input, out Int32 value ) ) // ideally use the overload with NumberStyles.Any and CultureInfo.CurrentCulture to be explicit.
{
Console.WriteLine( $"Output: {value}" );
}
else
{
Console.WriteLine( "Please enter a valid number." );
}
}