Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add and subtract in C#?

Tags:

c#

math

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.

like image 611
Jargon57 Avatar asked Oct 26 '25 16:10

Jargon57


1 Answers

This mix-up comes from the confusion between two roles of +:

  • When it is used in an expression with strings, it denotes concatenation
  • When it is used in an expression with numeric types, it denotes addition

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
like image 170
Sergey Kalinichenko Avatar answered Oct 29 '25 06:10

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!