Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

calculator in C#

using System;

class Program
{
    static void Main(string[] args)
    {
        float ans = 0;

        // Asking the user what operator to use by number
        Console.WriteLine("(1)Add
(2)Subtract
(3)Multiply
(4)Divide");
        Console.WriteLine("Enter an operator: ");
        int op = int.Parse(Console.ReadLine());

        // Asking the first number and parsing it to a float
        Console.WriteLine("Enter the first number: ");
        float n1 = float.Parse(Console.ReadLine());

        // Asking the second number and parsing it to a float
        Console.WriteLine("Enter the second number: ");
        float n2 = float.Parse(Console.ReadLine());

        // Checking the value of op and then doing the correct operation
        if (op == 1)
        {
            ans = n1 + n2;
        }
        else if (op == 2)
        {
            ans = n1 - n2;
        }
        else if (op == 3)
        {
            ans = n1 * n2;
        }
        else if (op == 4)
        {
            ans = n1 / n2;
        }
        else
        {
            Console.WriteLine("Error operator unknown");
        }     

        // Printing the answer
        Console.WriteLine("The answer is " + ans);
    }
}
 
PREVIOUS NEXT
Tagged: #calculator
ADD COMMENT
Topic
Name
1+6 =