How do I add and subtract in C #?
I am new to C # and I am trying to make a calculator. In Python (which I'm more familiar with), you simply import math
and then write down what you want to do with the math.
But from 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 that, first, gives me 23 if I try to add and throws a syntax error (Operator '-' cannot be applied to operands like 'string' and 'int'.) If I try to subtract.
I'm only new to this language, so I'm probably making stupid mistakes.
source to share
This confusion is due to the confusion between the two roles +
:
- When used in a string expression, it denotes concatenation
- When used in an expression with numeric types, it denotes addition
You can fix this problem by putting parentheses around your expressions.
However, it is best to use string formatting or string interpolation instead of concatenation, which avoids this problem altogether:
Console.WriteLine("The result is {0}", num01 - num02); // Formatting
or
Console.WriteLine($"The result is {num01 - num02}"); // Interpolation
source to share
just order your operations with ()
.
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();
}
}
}
source to share
The order of operations is really important for strongly typed languages ββlike Java and C #. Like many already answered, you first add a string to the first number and then try to subtract from the string.
This is what your code does:
1. "The result is " + num01 - num02
2. "The result is (value of num01)" - num02
3. Error when trying to subtract
Changing it to
Console.WriteLine("The result is " + (num01 - num02));
Your code runs like this:
1. "The result is " + (num01 - num02)
2. "The result is " + (difference of num01 and num02)
3. "The result is (difference of num01 and num02)"
Hope it helps
source to share