Kode Program Pembuatan Sederhana Kalkulator C#
using System;
namespace Calculator
{
class Calculator
{
public static double DoOperation(double num1, double num2, string op)
{
double result = double.NaN; // Default value is "not-a-number" which we use if an operation, such as division, could result in an error.
// Use a switch statement to do the math.
switch (op)
{
case "a":
result = num1 + num2;
break;
case "s":
result = num1 - num2;
break;
case "m":
result = num1 * num2;
break;
case "d":
// Ask the user to enter a non-zero divisor.
if (num2 != 0)
{
result = num1 / num2;
}
break;
// Return text for an incorrect option entry.
default:
break;
}
return result;
}
}
class Program
{
static void Main(string[] args)
{
bool endApp = false;
// Display title as the C# console calculator app.
Console.WriteLine("kalkulator C#\r");
Console.WriteLine("------------------------\n");
while (!endApp)
{
// Declare variables and set to empty.
string numInput1 = "";
string numInput2 = "";
double result = 0;
// Ask the user to type the first number.
Console.Write("Ketik nomor awal, lalu tekan Enter: ");
numInput1 = Console.ReadLine();
double cleanNum1 = 0;
while (!double.TryParse(numInput1, out cleanNum1))
{
Console.Write("Ini bukan masukan yang valid. Harap masukkan nilai integer: ");
numInput1 = Console.ReadLine();
}
// Ask the user to type the second number.
Console.Write("Ketik nomor kedua, lalu tekan Enter: ");
numInput2 = Console.ReadLine();
double cleanNum2 = 0;
while (!double.TryParse(numInput2, out cleanNum2))
{
Console.Write("Ini bukan masukan yang valid. Harap masukkan nilai integer: ");
numInput2 = Console.ReadLine();
}
// Ask the user to choose an operator.
Console.WriteLine("Pilih operator dari daftar berikut:");
Console.WriteLine("\ta - penambahan");
Console.WriteLine("\ts - pengurangan");
Console.WriteLine("\tm - perkalian");
Console.WriteLine("\td - pembagian");
Console.Write("silahkan dipilih ");
string op = Console.ReadLine();
try
{
result = Calculator.DoOperation(cleanNum1, cleanNum2, op);
if (double.IsNaN(result))
{
Console.WriteLine("Operasi ini akan menghasilkan kesalahan matematika.\n");
}
else Console.WriteLine("hasil anda: {0:0.##}\n", result);
}
catch (Exception e)
{
Console.WriteLine("Oh tidak! Pengecualian terjadi saat mencoba melakukan matematika.\n - Details: " + e.Message);
}
Console.WriteLine("------------------------\n");
Console.Write("Tekan 'n' dan Enter untuk menutup aplikasi, atau tekan tombol lain dan Enter untuk melanjutkan: ");
if (Console.ReadLine() == "n") endApp = true;
Console.WriteLine("\n");
}
return;
}
}
}
Komentar
Posting Komentar