Guyz finally figured out how to do the mdas prob...the problem is this...the user would input mathematical equations like 4+3*5 then the program would give u the answer...simple enough but theres more it should follow the mdas rule....took me weeks before i figured the mdas thing but finally done with it...but theres another problem...it should also be able to read negative integers...
![Shocked](images/smilies/shocked.gif)
...my brain is about to explode...this week is the deadline to pass this exercise and no one in the class is even near the answer...pls guyz i need ur help...heres the code...it works perfectly fine but no idea how to do the negative thing
Code:
static void Main(string[] args)
{
string qans = "yes";
do
{
Console.Write("Input Expression:");
string input = Console.ReadLine();
Calculate(input);
Console.WriteLine("\n\n\nAnother Expression[yes/no]: ");
qans = Console.ReadLine();
Console.Clear();
}while(qans== "yes");
Console.ReadLine();
}
private static void Calculate(string input)
{
try
{
string[] array = new string[input.Length];
string[] revarray = new string[input.Length];
const string operators = "+-*/";
if (input.Length == 0)
return;
char[] temp = input.ToCharArray();
string str = "";
int i = 0;
int ctr = 0;
int len = temp.Length;
foreach (char ch in temp)
{
if (Char.IsDigit(ch))
{
str += ch.ToString();
if (i == len - 1)
{
array[ctr] = str;
}
}
else
{
array[ctr] = str;
ctr = ctr + 1;
str = "";
if (operators.Contains(ch.ToString()))
{
array[ctr] = ch.ToString();
ctr = ctr + 1;
}
}
i++;
}
decimal tempans;
for (ctr = 0; ctr < input.Length; ctr++)
{
if (array[ctr] == "*")
{
tempans = decimal.Parse(array[ctr - 1]) * decimal.Parse(array[ctr + 1]);
array[ctr] = "+";
array[ctr - 1] = "0";
array[ctr + 1] = tempans.ToString();
}
if (array[ctr] == "/")
{
tempans = decimal.Parse(array[ctr - 1]) / decimal.Parse(array[ctr + 1]);
array[ctr] = "+";
array[ctr - 1] = "0";
array[ctr + 1] = tempans.ToString();
}
}
decimal ans = decimal.Parse(array[0]);
for (ctr = 1; ctr < input.Length; ctr = ctr + 2)
{
if (array[ctr] == "+")
{
ans = ans + decimal.Parse(array[ctr + 1]);
}
if (array[ctr] == "-")
{
ans = ans - decimal.Parse(array[ctr + 1]);
}
}
Console.WriteLine("The answer is: " + ans);
}
catch
{
Console.WriteLine("That Was An Invalid Entry!!!");
}
}