|
-
Mar 7th, 2007, 02:59 PM
#1
Thread Starter
Addicted Member
Parser/recursion problem
I have just written this small calculator, and it kinda works.
2+2 = 4
4+4 = 8
but
2+2+2 = 12
4-2 = -8
So there is obviosly some glitches, and i suspect the "recurrsion". I have tried lots of adjustments but none solves the problem. Maybe you see something that i dont:
Code:
using System;
using System.Collections.Generic;
using System.Text;
namespace minicalc
{
class Program
{
public static String input, tmpexp; // Expression
public static int length; // Lenght of input
public static int curPos; // Current token
public static int value, temp = 0; // value holders
public static String Op;
static void Main(string[] args)
{
System.Console.WriteLine("Please enter expression to calculate: ");
input = System.Console.ReadLine();
length = input.Length;
curPos = 0;
while (curPos < length)
{
if (input[curPos] == '0' || input[curPos] == '1' || input[curPos] == '2' || input[curPos] == '3' || input[curPos] == '4' || input[curPos] == '5' || input[curPos] == '6' || input[curPos] == '7' || input[curPos] == '8' || input[curPos] == '9')
{
tmpexp += input[curPos];
}
temp += Convert.ToInt32(tmpexp);
Op = Convert.ToString(input[curPos ]);
// Determine which operator we have and use it on the result
switch (Op)
{
case "+": value += temp;
break;
case "-": value -= temp;
break;
case "*": value *= temp;
break;
}
curPos++;
}
System.Console.WriteLine("Result of calculation: " + value);
System.Console.ReadLine();
}
}
}
-
Mar 8th, 2007, 07:29 AM
#2
Re: Parser/recursion problem
Your logic is being naive. For each character in the input you are not only adding it to a class variable whose value may have been set in the previous iteration but you are also checking to see if it is an operator.
You should rewrite your if statements in such a way that it determines if it is a number, operator or junk (blank space). In addition, don't go on a character by character basis. Take the number as a whole until you reach an operator or a blank space, this way you can get 22, for example.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|