I am new to C# and I am trying to make a calculator. In Python(which I am more familiar with), You just import mathand then write out what it is you want to do with math.
But with C#, this is my code:
using system;
namespace Calculator
{
class MainClass
{
public static void Main(string[] args)
{
divide(2,3);
}
public static void add(int num01, int num02)
{
Console.WriteLine("The result is " + num01+num02);
Console.ReadKey();
}
public static void multiply(int num01, int num02)
{
Console.WriteLine("The result is " + num01 * num02);
Console.ReadKey();
}
public static void divide(double num01, double num02)
{
Console.WriteLine("The result is " + num01 / num02);
Console.ReadKey();
}
public static void subtract(int num01, int num02)
{
Console.WriteLine("The result is " + num01 - num02);
Console.ReadKey();
}
}
}
And it firstly gives me 23 if I try to add, and throws a syntax error( Operator '-' cannot be applied to operands of type 'string' and 'int'.) if I try to subtract.
I'm only new to this language so I'm probably making some silly mistakes.
This mix-up comes from the confusion between two roles of +:
You can fix this problem by placing parentheses around your expressions.
However, a better approach is to use string formatting or string interpolation instead of concatenation, which lets you avoid this problem altogether:
Console.WriteLine("The result is {0}", num01 - num02); // Formatting
or
Console.WriteLine($"The result is {num01 - num02}"); // Interpolation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With