当前位置:网站首页>新手入门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();//循环输入
}
}
}
上机实践:
边栏推荐
猜你喜欢
随机推荐
JS Bom location 楼层导航效果 offsetTop data-n 方括号选择器
VLAN 实验
【C语言刷LeetCode】2295. 替换数组中的元素(M)
Postgresql daily operation and maintenance skills, suitable for beginners
Hacker News Broadcast | A fake offer steals $625 million
LeetCode 2342. Digital and equal number of one of the biggest and
Dell's first pure soft product redefines next-generation object storage
使用SqlSessionFactory工具类抽取
记一次搭建conda虚拟环境
多线程---初阶
English语法_不定代词 -some & any
Type-C边充电边OTG芯片——LDR6028A
DAP数据加工流程梳理
一个塑料瓶的海洋“奇幻漂流”
力扣刷题训练(二)
解决:npm ERR code ELIFECYCLE npm ERR errno 1(安装脚手架过程中,在npm run dev 时发生错误)
Fudan-Washington University EMBA Kechuang's Ao E丨The Magical Materials and We Are Shaped
实现导入市场活动:
go jwt use
【笔记】结巴分词绘制词云图









