我刚刚开始在C#中,我做了这个非常简单的计算器。首先,你对我的代码有什么看法,有什么我应该改进的地方?其次,当我要求用户输入2个数字时,我怎样才能让他只能输入数字?如果用户键入不同的字符,循环会卡住并且程序崩溃。如何只允许用户输入数字
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace App1
{
class Program
{
static void Main(string[] args)
{
bool retry = true;
while (retry)
{
retry = true;
double x1;
double x2;
double x3;
string calc;
Console.WriteLine("**** Hello, Welcome to Calculator ****");
Console.WriteLine("Type a number please: ");
x1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("\n Now type another number: ");
x2 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("\n Now please select a calculation:(/,*,+/-)");
calc = Convert.ToString(Console.ReadLine());
if (calc == "*")
{
x3 = (x1 * x2);
Console.WriteLine("\n Your Numbers equal = " + x3);
retry = false;
}
else if (calc == "/")
{
x3 = (x1/x2); Console.WriteLine("\n Your Numbers equal = " + x3);
retry = false;
}
else if (calc == "+")
{
x3 = (x1 + x2);
Console.WriteLine("\n Your Numbers equal = " + x3);
retry = false;
}
else if (calc == "-")
{
x3 = (x1 - x2);
Console.WriteLine("\n Your Numbers equal = " + x3);
retry = false;
}
else
{
Console.WriteLine("\n Error, please type one of the 4 calculations: ");
retry = true;
}
//Don't Exit:
Console.ReadKey();
//Don't Exit:
}
}
}
}
非常感谢,但不是我的代码说x1和x2没有任何价值。 – user1930233
对不起,错过了。检查编辑。 – stybl
美妙,作品完美。也会像你说的那样查看switch语句, – user1930233