如何适应我的一位数计算器工作与任何长度的任何数字(实数)
本文关键字:任何长 任何 实数 数字 工作 我的 何适应 一位 计算器 | 更新日期: 2023-09-27 18:13:03
所以我有这个代码,我一直在努力使它适应任何数量的实数,似乎研究微软网站还没有成功,所以我在这里作为我的最后一招。
char operation;
String calculation;
double num1, num2, ans;
Console.WriteLine("Place your calculation in the form (x'symbol'y)");
calculation = Console.ReadLine();
num1 = double.Parse(calculation[0].ToString());
num2 = double.Parse(calculation[2].ToString());
operation = calculation[1];
switch (operation)
{
case '+':
ans = num1 + num2;
Console.WriteLine(num1 + num2);
break;
case '-':
ans = num1 - num2;
Console.WriteLine(num1 - num2);
break;
case '/':
ans = num1 / num2;
Console.WriteLine(num1 / num2);
break;
case '*':
ans = num1 * num2;
Console.WriteLine(num1 * num2);
break;
}
下面是一个示例,说明如何使用Regex并遵循您提供的格式来处理任何长度的数字。正如评论中所述,Compute()是一种更简单的方法来使其工作!
char operation;
string calculation;
double num1, num2, ans;
Regex validcheck = new Regex(@"^'d+([+]|[-]|[/]|[*])'d+$");
Regex findnumber = new Regex(@"'d+");
Regex findoperation = new Regex(@"([+]|[-]|[/]|[*])");
Console.WriteLine("Place your calculation in the form (x'symbol'y)");
calculation = Console.ReadLine();
if (validcheck.IsMatch(calculation))
{
num1 = double.Parse(findnumber.Matches(calculation)[0].Value);
num2 = double.Parse(findnumber.Matches(calculation)[1].Value);
operation = char.Parse(findoperation.Match(calculation).Value);
switch (operation)
{
case '+':
ans = num1 + num2;
Console.WriteLine(num1 + num2);
break;
case '-':
ans = num1 - num2;
Console.WriteLine(num1 - num2);
break;
case '/':
ans = num1 / num2;
Console.WriteLine(num1 / num2);
break;
case '*':
ans = num1 * num2;
Console.WriteLine(num1 * num2);
break;
}
}
else
{
Console.WriteLine("The operation you inserted has an invalid format");
}
Console.Read();
在代码num2 = double.Parse(calculation[0].ToString());
的第七行你应该写num2 = double.Parse(calculation[2].ToString());
第二部分我还在努力解决。
做了类似的事情,除了我只使用一个正则表达式,然后为数字和操作符索引组捕获。
char operation;
String calculation;
double num1, num2, ans;
Console.WriteLine("Place your calculation in the form (x'symbol'y)");
calculation = Console.ReadLine();
Regex testRegex = new Regex(@"([0-9]*)([+-/*])([0-9]*)");
var match = testRegex.Match(calculation);
if (!match.Success)
{
Console.WriteLine("Invalid syntax");
return;
}
num1 = double.Parse(match.Groups[1].Value);
num2 = double.Parse(match.Groups[3].Value);
operation = match.Groups[2].Value[0];
switch (operation)
{
case '+':
ans = num1 + num2;
Console.WriteLine(num1 + num2);
break;
case '-':
ans = num1 - num2;
Console.WriteLine(num1 - num2);
break;
case '/':
ans = num1 / num2;
Console.WriteLine(num1 / num2);
break;
case '*':
ans = num1 * num2;
Console.WriteLine(num1 * num2);
break;
}