Loading...

Във форума е въведено ограничение, което позволява на потребителите единствено да разглеждат публикуваните въпроси.

Tihomirtx88 avatar Tihomirtx88 9 Точки

Може ли малко помощ на задача Operations Between Numbers ?

Не мога да открия къде в делението ми е грешката и как да създам условие при деление  0 да ми изписва 

  • "Cannot divide {N1} by zero"

 

using System;

namespace OperationsBetweenNumbers
{
    class Program
    {
        static void Main(string[] args)
        {
            int numberOne = int.Parse(Console.ReadLine());
            int numberTwo = int.Parse(Console.ReadLine());
            string operatorOne = Console.ReadLine();
            double result = 0;
            if (operatorOne == "+")
            {
                result = numberOne + numberTwo;
                if (result % 2 == 0)
                {
                    Console.WriteLine($" {numberOne} {operatorOne} {numberTwo} = {result} - even");
                }
                else
                {
                    Console.WriteLine($" {numberOne} {operatorOne} {numberTwo} = {result} - odd");
                }
            }
            else if (operatorOne == "-")
            {
                result = numberOne - numberTwo;
                if (result % 2 == 0)
                {
                    Console.WriteLine($" {numberOne} {operatorOne} {numberTwo} = {result} - even");
                }
                else
                {
                    Console.WriteLine($" {numberOne} {operatorOne} {numberTwo} = {result} - odd");
                }
            }
            else if (operatorOne == "*")
            {
                result = numberOne * numberTwo;
                if (result % 2 == 0)
                {
                    Console.WriteLine($" {numberOne} {operatorOne} {numberTwo} = {result} - even");
                }
                else
                {
                    Console.WriteLine($" {numberOne} {operatorOne} {numberTwo} = {result} - odd");
                }
            }
            else if (operatorOne == "/")
            {
                result = numberOne / numberTwo;
                Console.WriteLine($" {numberOne} / {numberTwo} = {result:f2}");
            }
            else if (operatorOne == "%")
            {
                result = numberOne % numberTwo;
                Console.WriteLine($" {numberOne} % {numberTwo} = {result}");
            }
            else if (numberTwo == 0)
            {
                Console.WriteLine($"Cannot divide {numberOne} by zero");
            }
        }
    }
}
 

Тагове:
0
Programming Basics with C#
kkaraivanov avatar kkaraivanov 486 Точки

Проверката за делене на 0 я слагаш в if-а като си правиш втори за 0-лата. Пробвай този код с по различен подход, сложил съм проверка за 0.

static void Main(string[] args)
        {
            double num1 = double.Parse(Console.ReadLine());
            double num2 = double.Parse(Console.ReadLine());
            char operat = char.Parse(Console.ReadLine());
            // "+", "-", "*", "/", "%"
            double result = 0;
            bool chekZero = false;

            switch (operat)
            {
                case '+':
                    result = num1 + num2;
                    break;
                case '-':
                    result = num1 - num2;
                    break;
                case '*':
                    result = num1 * num2;
                    break;
                case '/':
                    result = num1 / num2;
                    if (num2 == 0)
                    {
                        chekZero = true;
                    }
                    break;
                case '%':
                    result = num1 % num2;
                    if (num2 == 0)
                    {
                        chekZero = true;
                    }
                    break;
                default:
                    break;
            }

            if (operat == '+' || operat == '-' || operat == '*')
            {
                string eventResult = "";
                if (result % 2 == 0)
                {
                    eventResult = "even";
                }
                else
                {
                    eventResult = "odd";
                }
                Console.WriteLine($"{num1} {operat} {num2} = {result} - {eventResult}");
            }
            else if (operat == '/')
            {
                if (!chekZero)
                {
                    Console.WriteLine($"{num1} / {num2} = {result:f2}");
                }
                else
                {
                    Console.WriteLine($"Cannot divide {num1} by zero");
                }
            }
            else if (operat == '%')
            {
                if (!chekZero)
                {
                    Console.WriteLine($"{num1} % {num2} = {result}");
                }
                else
                {
                    Console.WriteLine($"Cannot divide {num1} by zero");
                }

            }
        }

 

0
23/02/2021 12:06:41
Tihomirtx88 avatar Tihomirtx88 9 Точки

Супер работи, само трябва да вникна в всички операции които правиш и накрая защо обръщаш true - false ,отново ти благодаря :)

0
kkaraivanov avatar kkaraivanov 486 Точки

Здравей. На въпроса свързан с булевата, не обръщам true-false, а ползвам дефолтната стойност. Пускам ти друго решение със същия код, като се постарах максимално да го синтезирам и опростя, за да можеш да проследиш какво се случва в предишния код.

static void Main(string[] args)
        {
            double num1 = double.Parse(Console.ReadLine());
            double num2 = double.Parse(Console.ReadLine());
            char operat = char.Parse(Console.ReadLine());
            double result = 0;

            switch (operat)
            {
                case '+':
                    result = num1 + num2;
                    PrintEvenOrOdd(num1, '+', num2, result);
                    break;
                case '-':
                    result = num1 - num2;
                    PrintEvenOrOdd(num1, '-', num2, result);
                    break;
                case '*':
                    result = num1 * num2;
                    PrintEvenOrOdd(num1, '*', num2, result);
                    break;
                case '/':
                    result = num1 / num2;
                    PrintWithCheckForZero(num1, num2, result);
                    break;
                case '%':
                    result = num1 % num2;
                    PrintWithCheckForZero(num1, num2, result);
                    break;
                default:
                    break;
            }
        }

        private static void PrintEvenOrOdd(double num1, char operand, double num2, double value)
        {
            string eventResult = "";
            if (value % 2 == 0)
            {
                eventResult = "even";
            }
            else
            {
                eventResult = "odd";
            }

            Console.WriteLine($"{num1} {operand} {num2} = {value} - {eventResult}");
        }

        private static void PrintWithCheckForZero(double num1, double num2, double result)
        {
            if (num2 == 0)
            {
                Console.WriteLine($"Cannot divide {num1} by zero");
            }
            else
            {
                Console.WriteLine($"{num1} % {num2} = {result}");
            }
        }

 

0
23/02/2021 18:32:11
Tihomirtx88 avatar Tihomirtx88 9 Точки

Разбрах идеята на решението ти ,направих още едно по-просто ,но ме бъгва при деленето ,случайно да можеш да ми откриеш грешката в този вид решение ,благодаря предварително .

using System;

namespace proba
{
    class Program
    {
        static void Main(string[] args)
        {
            int numberOne = int.Parse(Console.ReadLine());
            int numberTwo = int.Parse(Console.ReadLine());
            string symbols = Console.ReadLine();
            double rezult = 0;
            if (symbols == "+")
            {
                rezult = numberOne + numberTwo;
                if (rezult % 2 == 0)
                {
                    Console.WriteLine($" { numberOne} + { numberTwo} = {rezult} - even ");
                    
                }
                else
                {
                    Console.WriteLine($" { numberOne} + { numberTwo} = {rezult} - odd ");
                }
            }
            else if (symbols == "-")
            {
                rezult = numberOne - numberTwo;
                if (rezult % 2 == 0)
                {
                    Console.WriteLine($" { numberOne} - { numberTwo} = {rezult} - even ");
                }
                else
                {
                    Console.WriteLine($" { numberOne} - { numberTwo} = {rezult} - odd ");
                }
            }
            else if (symbols == "*")
            {
                rezult = numberOne * numberTwo;
                if (rezult % 2 == 0)
                {
                    Console.WriteLine($" { numberOne} * { numberTwo} = {rezult} - even ");
                }
                else
                {
                    Console.WriteLine($" { numberOne} * { numberTwo} = {rezult} - odd ");
                }
            }
            else if (symbols == "%")
            {
                if (numberTwo != 0)
                {
                    rezult = numberOne % numberTwo;
                    Console.WriteLine($" { numberOne } % {numberTwo} = {rezult} ");

                }
                else
                {
                    Console.WriteLine($"Cannot divide {numberOne} by zero");
                }
            }
            else if (symbols == "/")
            {
                if (numberTwo != 0)
                {
                    rezult = numberOne / numberTwo;
                    Console.WriteLine($"{numberOne} / {numberTwo} = {rezult:f2} ");


                }
                else
                {
                    Console.WriteLine($"Cannot divide {numberOne} by zero");
                }
            }
           

        }
    }
}

0
27/02/2021 16:56:46
Можем ли да използваме бисквитки?
Ние използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Можете да се съгласите с всички или част от тях.
Назад
Функционални
Използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Използваме „сесийни“ бисквитки, за да Ви идентифицираме временно. Те се пазят само по време на активната употреба на услугите ни. След излизане от приложението, затваряне на браузъра или мобилното устройство, данните се трият. Използваме бисквитки, за да предоставим опцията „Запомни Ме“, която Ви позволява да използвате нашите услуги без да предоставяте потребителско име и парола. Допълнително е възможно да използваме бисквитки за да съхраняваме различни малки настройки, като избор на езика, позиции на менюта и персонализирано съдържание. Използваме бисквитки и за измерване на маркетинговите ни усилия.
Рекламни
Използваме бисквитки, за да измерваме маркетинг ефективността ни, броене на посещения, както и за проследяването дали дадено електронно писмо е било отворено.