当前位置:网站首页>新手入门C#:实现简易的计算器功能
新手入门C#:实现简易的计算器功能
2022-07-30 02:29:00 【最早的早安...】
题目概述:
使用C#实现一个加减乘除的计算器。
编程:
namespace ConsoleApp1
{
class Program
{
static string[] ary = new string[] { "+", "-", "*", "/" };
private static int A(string inputStr, ref int calcType)//输入:字符串 输出:运算符在该字符串的位置和该运算符(calcType)
{
int index = -1;
for (int i = 0; i < ary.Length; i++)
{
string tag = ary[i];
index = inputStr.IndexOf(tag);//查找tag在字符串中的位置
if (index != -1)
{
calcType = i;
break;
}
}
return index;
}
private static void CalcResult(string inputStr, int calcType, int index)
{
string numStr1 = inputStr.Substring(0, index);//下标为0,开始的长度为index的子字符串
int strlen = inputStr.Count();
string numStr2 = inputStr.Substring(index + 1, strlen - index - 1);
float num1 = float.Parse(numStr1);
float num2 = float.Parse(numStr2);
float result = 0;
switch (calcType)
{
case 0: result = num1 + num2; break;
case 1: result = num1 - num2; break;
case 2: result = num1 * num2; break;
case 3: result = num1 / num2; break;
default: break;
}
Console.WriteLine($"{inputStr}的计算结果为:{result}");
}
static void Main()
{
while (true)
{
Console.WriteLine("请输入算数题(只支持加减乘除),按回车结束输入");
string inputStr = Console.ReadLine();//输入字符串
int calcType = -1;
int index = A(inputStr, ref calcType);
if (calcType == -1)
{
Console.WriteLine("输入运算符有误!");
break;
}
CalcResult(inputStr, calcType, index);
}
Console.ReadLine();//循环输入
}
}
}
上机实践:
边栏推荐
猜你喜欢

flutter学习之widget的显示和隐藏

Unity Editor自定义一个记录Bug的窗口

RAII Technology Learning

表达式计算器 ExpressionRunner

【ModelArts系列】华为ModelArts训练yolov3模型(训练管理)

超详细的MySQL基本操作

Using ESP32 construct a ZIGBEE network adapter

机器学习(十五)异常检测

houdini 使用HDA Processor 实现处理HDA输入输出

The box office broke 790 million US dollars. Have you watched this recent dinosaur movie?
随机推荐
实现导入市场活动:
错误:“filesystem“ 不是 “std“ 的成员
ROS 2知识:通信协议 DDS/RTPS
About offline use of SAP Fiori apps
浏览器缓存机制
实现批量导出功能
超详细的MySQL三万字总结
票房破7.9亿美元,最近这部恐龙爽片你看了吗?
成功解决pydotplus.graphviz.InvocationException: GraphViz‘s executables not found
houdini 使用HDA Processor 实现处理HDA输入输出
ButtonStyle, MaterialStateProperty learned by flutter
go grpc custom interceptor
JS develops 3D modeling software
MIT6.S081 小结
自动配置和 thymeleaf模板引擎
A transaction is in Mysql?What's the use?
菜刀、冰蝎、蚁剑、哥斯拉的流量特征
Leetcode.19 删链表倒数第 N 个结点(栈/先后指针)
【服务器存储数据恢复】华为OceanStor某型号存储raid5数据恢复案例
STM32L4R9ZIY6PTR STM32L4高性能嵌入式—MCU