
C#高手帮忙 不断要求用户输入一个数字,然后打印这个数字的二倍,当用户输入q的时候程序退出
while(true){Console.WriteLine("请输入数字");strings1=Console.ReadLine();if(s1=="q"){return...
while (true)
{
Console.WriteLine("请输入数字");
string s1 = Console.ReadLine();
if (s1 == "q")
{
return;
}
else
{
int a1 = Convert.ToInt32(s1);
a1 = a1 * a1;
Console.WriteLine(a1);
}
Console.ReadKey();
我这么写后生成的时候没有问题,当运行的时候就出BUG了。。问题出在哪了?
提示转换Convert.Toint32(s1);有问题 展开
{
Console.WriteLine("请输入数字");
string s1 = Console.ReadLine();
if (s1 == "q")
{
return;
}
else
{
int a1 = Convert.ToInt32(s1);
a1 = a1 * a1;
Console.WriteLine(a1);
}
Console.ReadKey();
我这么写后生成的时候没有问题,当运行的时候就出BUG了。。问题出在哪了?
提示转换Convert.Toint32(s1);有问题 展开
3个回答
展开全部
因为你最后Console.ReadKey();是读取键盘输入的值,所以回车键也算做输入内容,格式提示转换错误.
while (true)
{
Console.WriteLine("请输入数字");
string s1 = Console.ReadLine();
int s = 0;
try
{
s = Convert.ToInt32(s1);
if (s1 == "q")
{
Console.WriteLine("操作完毕");
break;
}
else
{
int a1 = Convert.ToInt32(s1);
a1 = a1 * a1;
Console.WriteLine(a1);
}
}
catch(Exception err)
{
Console.WriteLine("请输入数字");
continue;
}
}
while (true)
{
Console.WriteLine("请输入数字");
string s1 = Console.ReadLine();
int s = 0;
try
{
s = Convert.ToInt32(s1);
if (s1 == "q")
{
Console.WriteLine("操作完毕");
break;
}
else
{
int a1 = Convert.ToInt32(s1);
a1 = a1 * a1;
Console.WriteLine(a1);
}
}
catch(Exception err)
{
Console.WriteLine("请输入数字");
continue;
}
}
展开全部
while (true)
{
Console.WriteLine("请输入数字");
string s1 = Console.ReadLine();
if (s1 == "q")
{
return;
}
else
{
int a1 = Convert.ToInt32(s1);
a1 = a1 * a1;
Console.WriteLine(a1);
}
1.去掉Console.ReadKey();
2.这段代码不能接收出“q”以外的其它字符(除数字),否则提示转换错误
可以在接收输入后判断是否是数字避免转换报错
{
Console.WriteLine("请输入数字");
string s1 = Console.ReadLine();
if (s1 == "q")
{
return;
}
else
{
int a1 = Convert.ToInt32(s1);
a1 = a1 * a1;
Console.WriteLine(a1);
}
1.去掉Console.ReadKey();
2.这段代码不能接收出“q”以外的其它字符(除数字),否则提示转换错误
可以在接收输入后判断是否是数字避免转换报错
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
楼主什么意思?怎么提这个问题?既然是将string转换成int,可是如果你输入的不是int而是aaa 或者bbb 这个转换怎么可能会成功呢?使用这则表达式进行输入的东西的验证
if (!Regex.IsMatch(s1, @"^[+-]?\d*$"))
{
Console.Write("请输入数字,进行计算!");
}
else
{
int a1 = Convert.ToInt32(s1);
a1 = a1 * a1;
Console.WriteLine(a1);
}
if (!Regex.IsMatch(s1, @"^[+-]?\d*$"))
{
Console.Write("请输入数字,进行计算!");
}
else
{
int a1 = Convert.ToInt32(s1);
a1 = a1 * a1;
Console.WriteLine(a1);
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询