有时需要从控制台输入数字,就用到前面介绍的内容,数据转换,如:
int num=int.Pares(Console.ReadLine());
int num=Convert.ToInt32(Console.ReadLine());
上面两句代码效果相同,可以根据自己的习惯选择任意一种。
using System; namespace vscode1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("请输入1个数字?");
int num = ReadInt();
Console.WriteLine("你刚刚输入的数为" + num);
Console.WriteLine("你刚刚输入的数为{0}", num);//与上一句一样的效果,等价 Console.WriteLine("请输入你岁数?");
int age = ReadInt();
Console.WriteLine("你的岁数是{0}!", age);
}
public static int ReadInt()
{
int number = ;
do
{
try
{
//将根据提示输入的数字字符串转换成int型
//Console.ReadLine(),这个函数,是以回车判断字符串结束的 number = Convert.ToInt32(Console.ReadLine());//与下面的效果一样
number = System.Int32.Parse(Console.ReadLine());
return number;
}
catch
{
Console.WriteLine("输入有误,重新输入!");
}
}
while (true);
}
}
}
输出结果:
你刚刚输入的数为22
你刚刚输入的数为22
请输入你岁数? 你的岁数是22!
参考文章:https://blog.csdn.net/u012110719/article/details/41379535