如何用C#写一个四则混合运算程序(要求用控制台程序)

要求实现四则混合运算的所有定律,并有菜单选项,还希望实现乘方和开方。(这是课程设计作业啊,希望高手帮忙)。

using System;
using System.Collections.Generic;
using System.Text;

namespace Count
{
//定义枚举类型存储运算方式
enum sign : byte
{
加 = 1,
减 = 2,
乘 = 3,
除 = 4,
乘方 = 5,
开方 = 6,
}
//定义一个算术结构(因为用于计算的变量只存储一些数据,用结构更好)
struct count
{
public double value1; //定义变量保存数字
public double value2;
public sign mySign; //使用枚举类型
}
class Program
{
private static count myCount;
static void Main(string[] args)
{
string answer; //定义变量存放是否继续计算
int input; //定义变量存放用户的选择
Console.WriteLine("--------欢迎使用运算程序--------\n");
do
{
Console.WriteLine("请选择您需要的运算类型:1.四则运算 2.乘方 3.开方");
input = Convert.ToInt32(Console.ReadLine());
switch (input) //判断用户的输入
{
case 1:
Console.WriteLine("请分别输入用于计算的数字");
Console.Write("请输入第一条数字:");
myCount.value1 = Convert.ToDouble(Console.ReadLine());
Console.Write("请输入第二条数字:");
myCount.value2 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("请选择运算方式: 1.加法 2.减法 3.乘法 4.除法");
input = Convert.ToInt32(Console.ReadLine());
if (input <= 4) //如果运算类型是“四则运算”
{
myCount.mySign =(sign)input;
}
else
{
Console.WriteLine("请正确选择运算方式: 1.加法 2.减法 3.乘法 4.除法");
}
WriteResult();
break;
case 2://用户选择乘方
myCount.mySign = sign.乘方;
Console.Write("请输入底数:");
myCount.value1 = Convert.ToDouble(Console.ReadLine());
Console.Write("请输入指数:");
myCount.value2 = Convert.ToDouble(Console.ReadLine());
WriteResult();
break;
case 3://用户选择开方
myCount.mySign = sign.开方;
Console.Write("请输入一条数字:");
myCount.value1 = Convert.ToDouble(Console.ReadLine());
WriteResult();
break;
default:
Console.WriteLine("请选择正确的运算类型:1.四则运算 2.乘方 3.开方");
break;
}
Console.WriteLine("\n继续运算吗?(y/n)");
answer = Console.ReadLine();
} while (answer.ToLower() == "y");

}
/// <summary>
/// 输出运算结果
/// </summary>
/// <param name="myCount"></param>
private static void WriteResult()
{
double result=0;
if (myCount.mySign <=(sign) 4)
{
switch (myCount.mySign)
{
case (sign)1:
result = myCount.value1 + myCount.value2;
break;
case (sign)2:
result = myCount.value1 - myCount.value2;
break;
case (sign)3:
result = myCount.value1 * myCount.value2;
break;
case (sign)4:
result = myCount.value1 / myCount.value2;
break;
}
Console.WriteLine("{0}{1}{2}的结果是{3}", myCount.value1, (sign)myCount.mySign, myCount.value2, result);
}
else
{
switch (myCount.mySign)
{
case (sign)5:
result = Math.Pow(myCount.value1, myCount.value2);
Console.WriteLine("底数{0},指数{1}的幂是{2}",myCount.value1,myCount.value2,result);
break;
case (sign)6:
result = Math.Sqrt(myCount.value1);
Console.WriteLine("{0}的平方根是{1}",myCount.value1,result);
break;
}
}
}
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2008-12-17
不支持负号,当然想用的话用 0- 代替 -

加减乘除括号以及若干函数,函数可以你自己添加。


if (aExp.Contains("sin"))
{
function(ref aExp, "sin");
}
这个地方加上就行了。

using System;
using System.Collections.Generic;
using System.Text;

namespace sizeyunsuan
{
class Program
{
static void Main(string[] args)
{
string a = Convert.ToString(23.0);

double value1 = 100 * (15 - 23 / (22.11 + 1.2341141242341142341251)) + 28.01 * Math.Sin(100);
double value2 = Arithmetic_expression.Calculate("100*(15-23/(22.11+1.2341141242341142341251))+28.01*sin(100)");

Console.WriteLine(value1.ToString());
Console.WriteLine(value2.ToString());

Console.ReadLine();
}
}

public class Arithmetic_expression
{
public static double Calculate(string aExp)
{
aExp = aExp.ToLower();
if (aExp.Contains("sin"))
{
function(ref aExp, "sin");
}

if (aExp.Contains("cos"))
{
function(ref aExp, "cos");
}

if (aExp.Contains("sqrt"))
{
function(ref aExp, "sqrt");
}

Stack<double> numStack = new Stack<double>();
Stack<char> opeStack = new Stack<char>();
opeStack.Push('#');

//Make a label end of string.
aExp += "#";
int pos = 0;

string tmpString = "";
//First, put numbers or operation into sracks.
while (pos < aExp.Length || opeStack.Peek() != '#')
{
if (!isNum(aExp[pos]))
{
switch (preOperator(aExp[pos], opeStack.Peek()))
{
case '>':
opeStack.Push(aExp[pos]);
pos++;
break;
case '<'://Calculate!
numStack.Push(compute(numStack.Pop(), numStack.Pop(), opeStack.Pop()));
break;
default:
opeStack.Pop();
pos++;
break;
}
tmpString = "";
}
else
{
if (numStack.Count > 0)
{
if (pos == 0)
{
numStack.Push(aExp[0]);
pos++;
continue;
}

if (!isNum(aExp[pos - 1]))
{
numStack.Push(0);
}

double tmpDouble = numStack.Pop();

if (aExp[pos] == '.')
{
}
else if (!tmpString.Contains(".") && aExp[pos - 1] != '.')
{
tmpDouble = tmpDouble * 10 + int.Parse(aExp.Substring(pos, 1));
}
else if (!tmpString.Contains(".") && aExp[pos - 1] == '.')
{
//Decimal.
tmpDouble = tmpDouble + int.Parse(aExp.Substring(pos, 1)) * 0.1;
}
else if (tmpString.Contains("."))
{
//Decimal.
int l = tmpString.Split(new char[1] { '.' })[1].Length + 1;
tmpDouble = tmpDouble + double.Parse(aExp[pos].ToString()) * Math.Pow(10, -l);
}
else
{
throw new Exception("It must be a true operation");
}

numStack.Push(tmpDouble);

tmpString += aExp[pos];
}
else
{
numStack.Push(int.Parse(aExp.Substring(pos, 1)));
}
pos++;
}
}
return numStack.Pop();// compute(numStack.Pop(), numStack.Pop(), opeStack.Pop());
}

private static void function(ref string aExp, string function)
{
string[] exp = aExp.Split(new char[] { '+', '-', '*', '/', '(', ')', ' ' }, StringSplitOptions.RemoveEmptyEntries);
int pos = aExp.IndexOf(function) + function.Length;
if (aExp[pos] == '(')
{
int countL = 1;
int countR = 0;
string tmp = "(";
for (pos = pos + 1; ; pos++)
{
if (countR == countL)
{
double value = MathF(function, Calculate(tmp));
aExp = aExp.Replace(function + tmp, value < 0 ? "(0" + value.ToString()+")" : value.ToString());
return;
}
else
{
tmp += aExp[pos];
if (aExp[pos] == ')')
{
countR++;
}
else if (aExp[pos] == '(')
{
countL++;
}
}
}
}
else
{
throw new Exception("It must be a true function");
}
}

private static double MathF(string fun, params object[] value)
{
fun = fun[0].ToString().ToUpper() + fun.Substring(1);
return (double)(typeof(Math).GetMethod(fun).Invoke(null, value));
}

private static bool isNum(char aChar)
{
char[] opeChars = { '+', '-', '*', '/', '(', ')', '#' };

if (Array.IndexOf(opeChars, aChar) >= 0)
{
return false;
}

if ((aChar < '0' || aChar > '9') && aChar != '.')
{
throw new Exception("It must be a true operation");
}

return true;
}

private static double compute(double d1, double d2, char aChar)
{
if (aChar == '*')
{
return d2 * d1;
}

if (aChar == '/')
{
if (d2 != 0)
{
return d2 / d1;
}
else
{
throw new Exception("The divisor is zero!");
}
}

if (aChar == '+')
{
return d2 + d1;
}
else
{
return d2 - d1;
}
}

private static char preOperator(char firstOpe, char secondOpe)
{
char[] addRank = { '+', '-' };
char[] multiRank = { '*', '/' };

if (Array.IndexOf(multiRank, firstOpe) >= 0 && Array.IndexOf(addRank, secondOpe) >= 0)
{
return '>';
}

if (secondOpe == '#')
{
return '>';
}

if (firstOpe == '#')
{
return '<';
}

if (firstOpe == '(')
{
return '>';
}

if (firstOpe == ')')
{
if (secondOpe == '(')
{
return '=';
}
else
{
return '<';
}
}

if (secondOpe == '(')
{
return '>';
}

return '<';
}
}
}
第2个回答  2008-12-16
可以去看下编译原理的书,方法是先把表达式转化成左式表示法,然后再来处理就简单多了
a+c -> +ac a+b*c -> +a*bc

a+b*c-d
转化成:
-+a*bcd

a*(b+c)/d
->
/*a+bcd
第3个回答  2008-12-24
在控制台中能做出来菜单吗??
这个作业太难了
要是应用程序还可以
第4个回答  2008-12-15
x加y = x+y
x减y = x-y
x乘以y = x*y
x除以y = x/y
x的y次方 = Math.Pow(x, y)
x的平方根 = Math.Sqrt(x)
相似回答