当前位置:网站首页>新手入门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();//循环输入
}
}
}
上机实践:
边栏推荐
猜你喜欢

五种绑定彻底弄懂this,默认绑定、隐式绑定、显式绑定、new绑定、箭头函数绑定详解

OSPF shamlink 解决后门链路问题

记一次搭建conda虚拟环境

一文读懂Elephant Swap,为何为ePLATO带来如此高的溢价?

机器学习1一回归模型(一)

躲避雪糕刺客?通过爬虫爬取雪糕价格

Type-C charging and OTG chip - LDR6028A

fluttter学习之ButtonStyle 、MaterialStateProperty

基于燃压缩空气储能系统的零碳微能源互联网优化调度(Matlab代码实现)

matlab洗碗机节水模型的优化设计-这是个课题名称,不是买洗碗机,审核的人仔细看下,谢谢
随机推荐
测试/开发程序员面试该如何谈薪资待遇呢?突破这个坎......
error: 'filesystem' is not a member of 'std'
nrm ls 为什么前面不带 *了
错误:“filesystem“ 不是 “std“ 的成员
固体火箭发动机三维装药逆向内弹道计算
Type-C charging and OTG chip - LDR6028A
记一次搭建conda虚拟环境
Oracle数据库表空间整理回收与释放操作
The role of diff and key
【C语言刷LeetCode】2295. 替换数组中的元素(M)
戴尔首款纯软产品,再定义下一代对象存储
复旦-华盛顿大学EMBA科创的奥E丨《神奇的材料》与被塑造的我们
go bidirectional streaming mode
博客搭建十:hugo博客添加友链
Houdini 地形知识点
Type-C边充电边OTG芯片——LDR6028A
解决:npm ERR code ELIFECYCLE npm ERR errno 1(安装脚手架过程中,在npm run dev 时发生错误)
零代码工具推荐---HiFlow
WebSocket在线通信
重写并自定义依赖的原生的Bean方法