Reputation: 13
I have this code, which is a part of a calculator I am currently making.
class Program
{
static void Main(string[] args)
{
string a = "6-3";/*This is supposed to be entered in a textbox by a user*/
int b = a.IndexOf(("-"));
string c = a.Substring(0, b);
int num1 = Convert.ToInt32(c);
int b2 = a.IndexOf(("-"));
string c2 = a.Substring(b);
int num2 = Convert.ToInt32(c2);
if(a.Contains("-"))
{
int an = num1 - num2;
string ans = Convert.ToString(an);
Console.WriteLine(ans);
}
}
}
The problem is that this results in 9 instead of 3, which it is supposed to output. And if i try the exact same code with division or multiplication the program crashes. Strange as it may seem, the code works perfectly with addition. Any help?
Upvotes: 1
Views: 98
Reputation: 112
that's because you make a substring of -3
, not 3
. string c2 = a.Substring(b);
should be string c2 = a.Substring(b+1);
a shorter version of this would be:
if(a.Contains("-"))
{
string[] nums = a.split('-')
Console.WriteLine( ((int)nums[0]) - ((int)nums[1]) )
}
Upvotes: 0
Reputation: 8224
It's because of this line:
string c2 = a.Substring(b);
c2
is equal to "-3" and so converts to -3
. 6 - -3
is 9.
Change the line to this:
string c2 = a.Substring(b + 1);
There are numerous other problems, the code needs serious refactoring but that's off topic a little.
Upvotes: 2
Reputation: 1438
When you substring c2
, b
is 1
. "6-3".Substring(1)
will return -3.
The substring parameters first input is how far forward to move. You need to move the index + 1 to move past the operator.
This makes your math problem 6 - - 3
Upvotes: 1