抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >
using System;
using System.Linq;

namespace Calculator
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 3; i++)
{
string inputStr = Console.ReadLine(); CalcOnline(inputStr);
}


}
static CalcInfo[] configs = new CalcInfo[]
{
new CalcInfo("+",(a,b)=>a+b),
new CalcInfo("-",(a,b)=>a-b),
new CalcInfo("*",(a,b)=>a*b),
new CalcInfo("/",(a,b)=>a/b),
};
private static void CalcOnline(string inputStr)
{
int index = -1;
Func<float, float, float> func = null;
for (int i = 0; i < configs.Length; i++)
{
var item = configs[i];
index = inputStr.IndexOf(item.tag);//找到符号,返回所在下标,未找到返回-1
if (index != -1)
{
func = item.func;//如果找到的是+,那么index为1,+的func函数内容是a+b
break;
}

}
if (index == -1)
{
Console.WriteLine("只支持+-*/");
return;
}
CalcResult(inputStr, func, index);
}

private static void CalcResult(string inputStr, Func<float, float, float> func, int index)
{
string num1Str = inputStr.Substring(0, index);//0~index之间的内容(不包括后面的)赋值给num1Str,若输入1+2则获得1
int strLen = inputStr.Count();
Console.WriteLine($"strLen:{strLen},index:{index}");
string num2Str = inputStr.Substring(index+1,strLen-index-1);//若输入1+2则获得2
float num1 = float.Parse(num1Str);
float num2 = float.Parse(num2Str);
Console.WriteLine($"num1:{num1}, num2:{num2}");
float result = func(num1, num2);
Console.WriteLine($"{inputStr}的计算结果:{result}");
}
}
public class CalcInfo
{
public string tag;
public Func<float, float, float> func;
public CalcInfo(string tag, Func<float, float, float> func)
{
this.tag = tag;
this.func = func;
}
}

}
//
//5+6
//strLen:3,index:1
//num1:5, num2:6
//5+6的计算结果:11

评论