15,665,718 members
1.00/5 (1 vote)
See more:
I have a simple calculator in C# Windows Form. It can perform basic calculation (i.e. Add, Subtract, Multiply, Division). But i can't calculate fraction calculation, example 3/2 / 1/2 = 3 (output). Any help please

What I have tried:

My basic code for Basic calculation:

C#
```switch (CalFunc)
{
case 1:
ResultAns = 1stNum - float.Parse(textBox1.Text);
textBox1.Text = ResultAns.ToString();
break;
case 2:
ResultAns = 1stNum + float.Parse(textBox1.Text);
textBox1.Text = ResultAns.ToString();
break;
case 3:
ResultAns = 1stNum * float.Parse(textBox1.Text);
textBox1.Text = ResultAns.ToString();
break;
case 4:

if (float.Parse(textBox1.Text) == 0)
{
textBox1.Text = "You cannot divide by zero";
return;
}
ResultAns = 1stNum / float.Parse(textBox1.Text);
textBox1.Text = ResultAns.ToString();
break;

case 5:
ResultAns = 1stNum / float.Parse(textBox1.Text);
textBox1.Text = ResultAns.ToString();
break;

default:
break;
}```
Posted
Updated 24-Feb-22 3:17am
v2

## Solution 1

You would need to change the whole way you are doing things: While it would be possible to correctly evaluate that if you replaces the final calculation with a constant:
`3/2/0.5 == 3`
When you try to do it by evaluating each operator immediately it gets teh wrong result:
`3/2/1/2 == 0.75`
Because
```3/2 == 1.5
1.5/1 == 1.5
1.5/2 == 0.75```
To get the correct result you would need to process the whole expression instead of individual "bits". One way to do that is to accept your inputs in Reverse Polish Notation instead of "normal math", but that's a PITA because nobody uses that in the real world so it's not likely to impress anyone that they have to learn a new way to enter numbers:
`3, 2, /, 1, 2, /, /`
is the RPN for what you want!
The other is to dump completely what you have and start again processing whole lines of an expression, and implementing operator precedence a well as brackets (which you need to evaluate your expression correctly:
`(3/2)/(1/2) == 3`
That's not trivial, but it is a good learning experience!

Maciej Los 24-Feb-22 13:34pm
5ed!

## Solution 2

Another technique is to use the input to cobble up a snippet of code (C# or VB), pass it to the .net compiler service, and then execute it or report any error messages produced.
But that's probably not what your teacher wants to see.

Compiling Source Code from a String[^]