# Simple Console Calculator

Page 1 of 1

## 2 Replies - 1032 Views - Last Post: 02 December 2012 - 01:29 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=302452&amp;s=75dbdec00ffe54c76f65afd222d2f62f&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 rideronix

Reputation: 1
• Posts: 25
• Joined: 24-November 12

# Simple Console Calculator

Posted 02 December 2012 - 11:25 AM

Hello everyone,
I'm trying to make a simple calculator that doesn't care about priority and only do operation linearly.
Example: 4 + 5 * 2 = 18

Here's my code so far:

```static void Main(string[] args)
{
int i = 0;
float res;
int p;
int num2 = 0;
int num1 = 0;

if (int.TryParse(args[1], out p))
{res = p;} // sets the res as the first number of the operation

while (i < args.Length) // Doing the whole length of what we enterd
{
switch (args[i])
{
case "+" : // If it detects a +

if (int.TryParse(args[i+1], out p)) // Take the next argument
{
num2 = Int32.Parse(args[i+1]); // Make it an int
res += num2; // Add it to res (which is the 1st argument and the total of before)
}
break;

case "-":

if (int.TryParse(args[i + 1], out p))
{
num2 = Int32.Parse(args[i + 1]);
res -= num2;
}
break;

case "*":

if (int.TryParse(args[i + 1], out p))
{
num2 = Int32.Parse(args[i + 1]);
res *= num2;
}
break;

} i++;
}
Console.WriteLine(res.ToString()); // Says unassigned res
}

```

However when I try it with a cmd, it crashes... Any ideas ?

This post has been edited by rideronix: 02 December 2012 - 11:28 AM

Is This A Good Question/Topic? 0

## Replies To: Simple Console Calculator

### #2 Momerath

• D.I.C Lover

Reputation: 1021
• Posts: 2,463
• Joined: 04-October 09

## Re: Simple Console Calculator

Posted 02 December 2012 - 12:48 PM

Arrays start from zero, so in line 9 you'd be trying to parse '+' into a int. It will fail so line 10 never executes.

You then go to your switch statement, which tests the first element (value '4' in this case) to see if it is a '+', a '-' or a '*'. It isn't any of those.

Line 20 you parse one of the values into an int. What do you think line 18 is doing? Why are you parsing the *exact same string* into an int twice? In consecutive lines, no less?

Your [i+1] stuff is going to get you in trouble, you should only ever parse the current element. What happens when the user enters "1 +"?

Assign a value to res in the line where you declare it in line 4.

### #3 tlhIn`toq

• Xamarin Cert. Dev.

Reputation: 6534
• Posts: 14,450
• Joined: 02-June 10

## Re: Simple Console Calculator

Posted 02 December 2012 - 01:29 PM

From my FAQ list:

[*]Q: I am making a calculator as my school homework project and ...
A: Calculator tutorial