
Originally Posted by
Thelastairbender
Mabuang ko sa amo exercise run...2 weeks na gyud ko nag trabaho ani di gyud na ko ma imagine unsaon...palihug kug tabang guyz...c# console application ra ni siya..not asking for spoon feed help pero pls guide me lang on the right track..hehehe
ang problem is ang user mo input ug mathematical expression like 78-93*62-87..dayun isud kuno tanang elements sa stack dayun iyang i compute ang result...mabuang gyud ko..unsaon man kuno nag tell sa program kung unsa ang number and unsa ang operations...ahhh kalibug...patabang lang ko guyz hap
Code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace ConsoleCalc
{
class Program
{
static void Main(string[] args)
{
Console.Write("Input Expression:");
string input = Console.ReadLine();
Calculate(input);
Console.ReadLine();
}
private static void Calculate(string input)
{
Decimal answer, currNum = 0;
string operand;
const string operators = "+-*/";
Stack revStack = new Stack();
Stack stack = new Stack();
if (input.Length == 0) // ignore if no input
return;
char[] temp = input.ToCharArray();
string str = "";
int i = 0;
int len = temp.Length;
foreach (char ch in temp)
{
if (Char.IsDigit(ch)) //is digit?
{
str += ch.ToString(); // store the digits temporarily, for multi-digits
if (i == len - 1) // is this the last?
{
stack.Push(str); // yes, push it.
}
}
else
{
// if the next char is not digit, probably operator, push your temp digits.
stack.Push(str);
str = ""; // clear temp
if (operators.Contains(ch.ToString())) // is token an operator?
stack.Push(ch); // yes, push it
}
i++;
}
// reverse the stack! it's upside down!!!
while (stack.Count > 0)
revStack.Push(stack.Pop());
// revStack is now in left to right order,
// top of stack to bottom. assign it to stack!
stack = revStack;
// calculate
// get the top of stack number. proper data validation
// would check each of the stack pops for expected token
// Use TryParse().
answer = Decimal.Parse(stack.Pop().ToString());
while (stack.Count > 0)
{
operand = stack.Pop().ToString();
currNum = Decimal.Parse(stack.Pop().ToString());
//1+2
answer = Arithmetic(answer, operand, currNum);
}
Console.WriteLine("The answer is " + answer.ToString() + ".");
}
private static Decimal Arithmetic(Decimal a, string oper, Decimal b)
{
Decimal result = 0;
switch (oper)
{
case "+":
result = a + b;
break;
case "-":
result = a - b;
break;
case "*":
result = a * b;
break;
case "/":
result = a / b;
break;
default:
break;
}
return result;
}
}
}