Как исключить деления на 0? - C#
Формулировка задачи:
Здравствуйте. Неделю назад начал учить С # и вот прошел несколько тем решил поиграть с консольным приложением. Но я не могу понять как исправить ошибку( деление на 0) в данном коде, хотя это даже не ошибка просто баг который я не могу поймать при деление на 0 консоль выдает -? а я хотел бы предупредить пользователя что деление на 0 невозможно.
Возможно кто-то из более опытных пользователей поможет.
Заранее благодарен!
Код:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace trenerovka2
{
class Program
{
static void Main(string[] args)
{
float first=0;
float second=0;
bool flag = false;
bool quit = false;
char operation = '\0';
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Instruction");
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write("[ ");
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("If you want to perform the operation subtraction, please write '-' and press Enter...");
Console.WriteLine(" If you want to perform multiplication operation, please write '*' and press Enter...");
Console.WriteLine(" If you want to perform the operation division, please write '/' and press Enter...");
Console.Write(" If you want to exit program, please write 'q' and press Enter...");
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write(" ]");
Console.WriteLine();
Console.WriteLine();
do
{
try
{
Console.ForegroundColor = ConsoleColor.Magenta;
Console.Write("Enter first numeric: ");
first = float.Parse(Console.ReadLine());
Console.Write("Enter second numeric: ");
second = float.Parse(Console.ReadLine());
Console.Write("Enter operation: ");
operation = char.Parse(Console.ReadLine());
}
catch
{
flag = true;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\aRead the manual");
Console.ForegroundColor = ConsoleColor.Magenta;
}
if (!flag)
{
Console.ForegroundColor = ConsoleColor.Blue;
switch (operation)
{
case '+': Console.WriteLine("Result: = " + (first + second)); break;
case '-': Console.WriteLine("Result: = " + (first - second)); break;
case '*': Console.WriteLine("Result: = " + (first * second)); break;
case '/': Console.WriteLine("Result: = " + (first / second)); break;
case 'q': quit = true; break;
default:
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\aRead the manual");
Console.ForegroundColor = ConsoleColor.Magenta;
}
break;
}
Console.ForegroundColor = ConsoleColor.Magenta;
Console.WriteLine();
}
flag = false;
}
while (!quit);
}
}
}Решение задачи: «Как исключить деления на 0?»
textual
Листинг программы
case '/':
if(second==0){
Console.WriteLine("На ноль делить низя!"); break;
}
else{
Console.WriteLine("Result: = " + (first / second)); break;
}