Visual studio как найти корень

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    In C#, Math.Sqrt() is a Math class method which is used to calculate the square root of the specified number. Sqrt is a slower computation. It can be cached for a performance boost. Syntax:

    public static double Sqrt(double d)

    Parameter:

    d: Number whose square root is to be calculated and type of this parameter is System.Double.

    Return Type: This method returns the square root of d. If d is equal to NaN, NegativeInfinity, or PositiveInfinity, that value is returned. The return type of this method is System.Double. Examples:

    Input  : Math.Sqrt(81) 
    Output : 9
    
    Input  : Math.Sqrt(-81) 
    Output : NaN
    
    Input  : Math.Sqrt(0.09) 
    Output : 0.3
    
    Input  : Math.Sqrt(0)
    Output : 0
    
    Input  : Math.Sqrt(-0)
    Output : 0

    Below C# programs illustrate the working of Math.Sqrt():

    • Program 1: When the argument is positive double value then this method returns the square root of a given value. 

    csharp

    using System;

    class GFG {

        public static void Main()

        {

            double x = 81;

            Console.Write(Math.Sqrt(x));

        }

    }

    • Program 2: When the argument is Negative, this method will return NaN. 

    csharp

    using System;

    class GFG {

        public static void Main()

        {

            double x = -81;

            Console.Write(Math.Sqrt(x));

        }

    }

    • Program 3: When the argument is double value with decimal places, then this method will return the square root of a given value. 

    csharp

    using System;

    class GFG {

        public static void Main()

        {

            double x = 0.09;

            Console.Write(Math.Sqrt(x));

        }

    }

    • Program 4: When the argument is positive or negative Zero, then it will return the result as Zero. 

    csharp

    using System;

    class GFG {

        public static void Main()

        {

            double x = 0;

            Console.WriteLine(Math.Sqrt(x));

            double y = -0;

            Console.Write(Math.Sqrt(y));

        }

    }

    Note: If the value is too large then it gives the compile time error as error CS1021: Integral constant is too large. Reference: https://msdn.microsoft.com/en-us/library/system.math.sqrt

    Last Updated :
    06 Sep, 2022

    Like Article

    Save Article

    Для выполнения различных математических операций в библиотеке классов .NET предназначен класс Math. Он является статическим, поэтому все его методы также являются статическими.

  • Abs(double value): возвращает абсолютное значение для аргумента value

    double result = Math.Abs(-12.4); // 12.4
    
  • Acos(double value): возвращает арккосинус value. Параметр value должен иметь значение от -1 до 1

    double result = Math.Acos(1); // 0
    
  • Asin(double value): возвращает арксинус value. Параметр value должен иметь значение от -1 до 1

  • Atan(double value): возвращает арктангенс value

  • BigMul(int x, int y): возвращает произведение x * y в виде объекта long

    double result = Math.BigMul(100, 9340); // 934000
    
  • Ceiling(double value): возвращает наименьшее целое число с плавающей точкой, которое не меньше value

    double result = Math.Ceiling(2.34); // 3
    
  • Cos(double d): возвращает косинус угла d

  • Cosh(double d): возвращает гиперболический косинус угла d

  • DivRem(int a, int b, out int result): возвращает результат от деления a/b, а остаток помещается в параметр result

    int result;
    int div = Math.DivRem(14, 5, out result);
    //result = 4
    // div = 2
    
  • Exp(double d): возвращает основание натурального логарифма, возведенное в степень d

  • Floor(decimal d): возвращает наибольшее целое число, которое не больше d

    double result = Math.Floor(2.56); // 2
    
  • IEEERemainder(double a, double b): возвращает остаток от деления a на b

    double result = Math.IEEERemainder(26, 4); // 2 = 26-24
    
  • Log(double d): возвращает натуральный логарифм числа d

  • Log(double a, double newBase): возвращает логарифм числа a по основанию newBase

  • Log10(double d): возвращает десятичный логарифм числа d

  • Max(double a, double b): возвращает максимальное число из a и b

  • Min(double a, double b): возвращает минимальное число из a и b

  • Pow(double a, double b): возвращает число a, возведенное в степень b

  • Round(double d): возвращает число d, округленное до ближайшего целого числа

    double result1 = Math.Round(20.56); // 21
    double result2 = Math.Round(20.46); //20
    
  • Round(double a, int b): возвращает число a, округленное до определенного количества знаков после запятой, представленного параметром b

    double result1 = Math.Round(20.567, 2); // 20,57
    double result2 = Math.Round(20.463, 1); //20,5
    
  • Sign(double value): возвращает число 1, если число value положительное, и -1, если значение value отрицательное. Если value равно 0, то возвращает 0

    int result1 = Math.Sign(15); // 1
    int result2 = Math.Sign(-5); //-1
    
  • Sin(double value): возвращает синус угла value

  • Sinh(double value): возвращает гиперболический синус угла value

  • Sqrt(double value): возвращает квадратный корень числа value

    double result1 = Math.Sqrt(16); // 4
    
  • Tan(double value): возвращает тангенс угла value

  • Tanh(double value): возвращает гиперболический тангенс угла value

  • Truncate(double value): отбрасывает дробную часть числа value, возвращаяя лишь целое значение

    double result = Math.Truncate(16.89); // 16
    
  • Также класс Math определяет две константы: Math.E и Math.PI. Например, вычислим площадь круга:

    Содержание

    • Тригонометрические функции (синус, косинус, тангенс)
    • Обратные тригонометрические функции (арккосинус, арксинус, арктангенс)
    • Гиперболические функции (гаперболический косинус, гиперболический синус, гиперболический тангенс)
    • Обратные гиперболические функции (ареакосинус, ареасинус, ареатангенс)
    • Вычисление логарифмов в C#
    • Методы округления чисел в C#
      • Сравнение различных методов округления в C#
    • Возведение в степень и извлечение корней в C#
    • Прочие математические операции
    • Константы класса Math
    • Итого

    уважаемые посетители блога, если Вам понравилась, то, пожалуйста, помогите автору с лечением. Подробности тут.

    Статический класс Math содержит ряд методов и констант для выполнения математических, тригонометрических, логарифмических и других операций. Так как класс статический, то и все его методы также являются статическими, т.е. вызывать эти методы можно без создания объекта типа Math. Рассмотрим основные методы этого класса.

    Все тригонометрические, обратные тригонометрические, гиперболические и обратные гиперболические методы в C# используют значения углов измеренных в радианах

    Тригонометрические функции (синус, косинус, тангенс)

    Cos(x) — возвращает косинус указанного угла x. Например,

    x = Math.Cos(1);//0,5403023058681398
    x = Math.Cos(0.5); //0,8775825618903728
    x = Math.Cos(0.75);//0,7316888688738209
    x = Math.Cos(-1);//0,5403023058681398
    

    Sin(x) — возвращает синус указанного угла x. Например,

    x = Math.Sin(1);//0,8414709848078965
    x = Math.Sin(0.5); //0,479425538604203
    x = Math.Sin(0.75);//0,6816387600233341
    x = Math.Sin(-1);//-0,8414709848078965

    Tan(x) — возвращает тангенс указанного угла x. Например,

    x = Math.Tan(1);//1,5574077246549023
    x = Math.Tan(0.5); //0,5463024898437905
    x = Math.Tan(0.75);//0,9315964599440725
    x = Math.Tan(-1);//-1,5574077246549023

    Обратные тригонометрические функции (арккосинус, арксинус, арктангенс)

    Acos(x) — вычисляет арккосинус заданного числа. Параметр x должен находиться в диапазоне от -1 до 1.  Значение, возвращаемое методом — радианы. Пример:

    x = Math.Acos(1); //0
    x = Math.Acos(0); //1,5707963267948966
    x = Math.Acos(-1);//3,141592653589793
    x = Math.Acos(0.5);//1,0471975511965979

    Asin(x) — вычисляет арксинус числа. Параметр x должен находиться в диапазоне от -1 до 1. Например,

    x = Math.Asin(1); //1,5707963267948966
    x = Math.Asin(0); // 0
    x = Math.Asin(10);//ошибка x>1
    x = Math.Asin(-1);//-1,5707963267948966
    x = Math.Asin(0.6);//0,6435011087932844
    

    Atan(x) — возвращает арктангенс числа. Значение, возвращаемое методом лежит в диапазоне от -Пи/2 до +Пи/2. Например,

    x = Math.Atan(1); //0,7853981633974483
    x = Math.Atan(0); //0 
    x = Math.Atan(10);//1,4711276743037347
    x = Math.Atan(-1);//-0,7853981633974483
    x = Math.Atan(0.6);//0,5404195002705842
    

    Atan2(x, y) — возвращает арктангенс для точки в декартовой системе координат с координатами (x,y). Например, 

    x = Math.Atan2(1,1); //0,7853981633974483
    x = Math.Atan2(1,-1); //2,356194490192345 
    x = Math.Atan2(-1,1);//-0,7853981633974483
    x = Math.Atan2(-1,-1);//-2,356194490192345
    

    Этот метод возвращает значение (θ), в зависимости от того, в каком квадранте располагается точка, а именно:

    • для (xy) в квадранте 1: 0 < θ < π/2.
    • для (xy) в квадранте 2: π/2 < θ ≤ π.
    • для (xy) в квадранте 3: -π < θ < -π/2.
    • для (xy) в квадранте 4: -π/2 < θ < 0.

    При этом стоит особо отметить, что точки могут лежать и за пределами указанных квадрантов, например, когда одна из координат равна нулю. В этом случае метод работает следующим образом:

    • если y равно 0, и x не является отрицательным, то θ = 0.
    • если y равно 0, и x является отрицательным, то θ = π.
    • если y — положительное число, а x равно 0, то θ = π/2.
    • если y — отрицательное число, а х равно 0, то θ = -π/2.
    • если y равен 0, и х равен 0, то θ = 0.

    Гиперболические функции (гаперболический косинус, гиперболический синус, гиперболический тангенс)

    Cosh(x) — вычисляет гиперболический косинус указанного угла

    x = Math.Cosh(1);//1,5430806348152437
    x = Math.Cosh(0.5); //1,1276259652063807
    x = Math.Cosh(0.75);//1,2946832846768448
    x = Math.Cosh(-1);//1,5430806348152437
    

    Sinh(x) — вычисляет гиперболический синус указанного угла

    x = Math.Sinh(1);//1,1752011936438014
    x = Math.Sinh(0.5); //0,5210953054937474
    x = Math.Sinh(0.75);//0,82231673193583
    x = Math.Sinh(-1);//-1,1752011936438014

    Tanh(x) — вычисляет гиперболический тангенс указанного угла

    x = Math.Tanh(1);//0,7615941559557649
    x = Math.Tanh(0.5); //0,46211715726000974
    x = Math.Tanh(0.75);//0,6351489523872873
    x = Math.Tanh(-1);//-0,7615941559557649
    

    Обратные гиперболические функции (ареакосинус, ареасинус, ареатангенс)

    Acosh(x) — вычисляет ареакосинус. Параметр x должен быть больше 1. Например,

    x = Math.Acosh(1); //0
    x = Math.Acosh(0); // ошибка - x<1
    x = Math.Acosh(10);//2,993222846126381
    x = Math.Acosh(3.14);//1,810991348900196
    x = Math.Acosh(10000);//9,903487550036129

    Asinh(x) — вычисляет ареасинус. Например,  

    x = Math.Asinh(1);//0,881373587019543
    x = Math.Asinh(0.5); //0,48121182505960347
    x = Math.Asinh(0.75);//0,6931471805599453
    x = Math.Asinh(-1);//-0,881373587019543

    Atanh(x) — вычисляет ареатангенс. Значение x должно быть в пределах от -1 до 1. Например,

    x = Math.Atanh(-0.5);//-0,5493061443340549
    x = Math.Atanh(0.5); //0,5493061443340549
    x = Math.Atanh(0.75);//0,9729550745276566
    x = Math.Atanh(-0.75);//-0,9729550745276566

    ILogB(x) —  вычисляет целочисленный логарифм с основанием 2 указанного числа, то есть значение (int)log2(x).

    x = Math.ILogB(15);//3

    Log2(x) — вычисляет логарифм с основанием 2 указанного числа.

    x = Math.Log2(15);//3,9068905956085187

    Log(x) — вычисляет натуральный логарифм (с основанием e) указанного числа.

    x = Math.Log(15);//2,70805020110221

    Log(x, y) — вычисляет логарифм указанного числа x по основанию y.

    x = Math.Log(15, 2);//3,9068905956085187

    Log10(x) — вычисляет логарифм с основанием 10 указанного числа

    x = Math.Log10(15);//1,1760912590556813

    Методы округления чисел в C#

    Ceiling(x) — возвращает наименьшее целое число, которое больше или равно заданному числу 

    x = Math.Ceiling(7.256);//8

    Floor(x) — возвращает наибольшее целое число, которое меньше или равно указанному числу 

    x = Math.Floor(7.256);//7

    Round(x) — округляет значение до ближайшего целого значения; значения посередине округляются до ближайшего четного числа

    x = Math.Round(7.256);//7

    Round(x, Int32 y) — округляет значение до указанного числа знаков после запятой; значения посередине округляются до ближайшего четного числа.

    x = Math.Round(7.256, 1);//7,3

    Round(x, Int32 y, MidpointRounding) — округляет значение до указанного числа дробных цифр, используя указанное соглашение о округлении

                x = Math.Round(7.256, 2, MidpointRounding.ToZero);//7,25
    x = Math.Round(7.256, 2, MidpointRounding.ToPositiveInfinity);//7,26
    x = Math.Round(7.256, 2, MidpointRounding.ToNegativeInfinity);//7,25
    x = Math.Round(7.256, 2, MidpointRounding.ToEven);//7,26

    Round(x, MidpointRounding) — округляет значение на целое число, используя указанное соглашение об округлении

    x = Math.Round(7.256, MidpointRounding.ToZero);//7

    Truncate(x) — вычисляет целую часть заданного числа 

    x = Math.Truncate(7.256);//7

    Сравнение различных методов округления в C#

    7,256 7,556 7,5
    Ceiling(x) 8 8 8
    Floor(x) 7 7 7
    Round(x) 7 8 8
    Round(x, 2) 7,26 7,56 7,5
    Round(x, ToZero) 7 7 7
    Round(x, 2, ToZero) 7,25 7,55 7,5
    Round(x, 2, ToPositiveInfinity) 7,26 7,56 7,5
    Round(x, 2, ToNegativeInfinity) 7,25 7,55 7,5
    Round(x, 2, ToEven) 7,26 7,56 7,5
    Truncate(x) 7 7 7

    Возведение в степень и извлечение корней в C#

    Cbrt(x) — возвращает кубический корень из x.

    x = Math.Cbrt(27);//3

    Exp(x) — возвращает e, возведенное в указанную степень x.

    x = Math.Exp(3);//20,085536923187668

    Pow(x, y) — возвращает число x, возведенное в степень y.

    x = Math.Pow(3,3);//27

    Sqrt(x) — возвращает квадратный корень из числа x.

    x = Math.Sqrt(9);//3

    Прочие математические операции

    Abs(x) — возвращает абсолютное значение числа

    x = Math.Abs(-2.7);//2.7
    x = Math.Abs(2.7);//2.7

    BigMul(Int32, Int32) — умножает два 32-битовых числа и возвращает значение в Int64.

    double x = Math.BigMul(Int32.MaxValue, Int32.MaxValue);//4,6116860141324206E+18

    BitDecrement(x) — возвращает ближайшее самое маленькое значение, которое меньше, чем x.

    x = Math.BitDecrement(1);//0,9999999999999999
    x = Math.BitDecrement(-1);//-1,0000000000000002

    BitIncrement(Double) — возвращает наименьшее ближайшее значение, которое больше указанного значения

    x = Math.BitIncrement(1);//1,0000000000000002
    x = Math.BitIncrement(-1);//-0,9999999999999999

    Clamp(x, min, max) — Возвращает x, ограниченное диапазоном от min до max включительно.

    x = Math.Clamp(3, 5, 10);//5
    x = Math.Clamp(4, 5, 10);//5
    x = Math.Clamp(11, 5, 10);//10

    CopySign(Double, Double) — возвращает значение с величиной x и знаком y.

    double x = Math.CopySign(-3, 5);//3 (знак + взят у 5)
    x = Math.CopySign(5, -10);//-5 (знак - взят у -10)

    DivRem(Int32, Int32, Int32) — Вычисляет частное чисел и возвращает остаток в выходном параметре

    x = Math.DivRem(-3, 5, out int y);//x = 0; y = -3
    x = Math.DivRem(10, 10, out int z);//x = 1; z = 0

    FusedMultiplyAdd(x, y, z) — возвращает значение (x * y) + z, округленное в рамках одной тернарной операции. 

    x = Math.FusedMultiplyAdd(10.4566d, 5.56012f, 10.83789f);//68,97784156904221
    x = (10.4566d * 5.56012f) + 10.83789f;                   //68,9778415690422
    

    Метод FusedMultiplyAdd округляет значение один раз — в конце вычислений, в то время как обычное вычисление (x * y) + z вначале округляет значение, полученное в скобках, затем добавляет к полученному значению z и ещё раз округляет результат.

    IEEERemainder(x, y) — Возвращает остаток от деления одного указанного числа на другое указанное число

    double x = Math.IEEERemainder(10, 3);//1

    Функция IEEERemainder не совпадает с оператором %, который также вычисляет остаток от деления. Различие заключается в формулах, используемых при вычислениях. Оператор действует следующим образом:

    a % b =  (Math.Abs(а) - (Math.Abs(b) * (Math.Floor(Math.Abs(a) / Math.Abs(b))))) * Math.Sign(a)  

    в то время, как метод IEEERemainder производит вычисления следующим образом:

    IEEERemainder(а,b) = a-(b * Math.Round(a/b))

    x = Math.IEEERemainder(-16.3, 4.1);//0,09999999999999787
    x = -16.3 % 4.1;//-4,000000000000002
    

    Max(x, y) — возвращает большее из чисел

    x = Math.Max(-16.3, 4.1);//4,1
    x = Math.Max(10, 5);//10

    MaxMagnitude(x, y) — возвращает большую величину из двух чисел двойной точности с плавающей запятой. При сравнении двух чисел не учитывается знак

    x = Math.MaxMagnitude(-16.3, 4.1);//-16,3
    x = Math.MaxMagnitude(10, 5);//10
    

    Min(Byte, Byte) — возвращает меньшее из двух чисел

    x = Math.Min(-16.3, 4.1);//-16,3
    x = Math.Min(10, 5);//5

    MinMagnitude(x, y) — возвращает меньшую величину из чисел. При сравнении не учитывается знак

    x = Math.MinMagnitude(-16.3, 4.1);//4.1
    x = Math.MinMagnitude(10, -5);//-5

    ScaleB(x, y) — Возвращает значение x * 2^n, вычисленное наиболее эффективно.

    x = Math.ScaleB(-16.3, 8);//4172,8

    Sign(x) — возвращает целое число, указывающее знак десятичного числа.

    x = Math.Sign(-16.3);//-1
    x = Math.Sign(10);//1
    x = Math.Sign(0);//0

    Константы класса Math

    В классе Math также определены две константы — E и PI:

    x = Math.E;//2,718281828459045
    x = Math.PI;//3,141592653589793

    Итого

    В статическом классе Math содержатся функции для тригонометрических, гиперболических и прочих вычислений. Кроме этого, класс содержит ряд методов округления чисел как в большую, так и меньшую сторону, а также методы для возведения чисел в степень и вычисления корней.

    уважаемые посетители блога, если Вам понравилась, то, пожалуйста, помогите автору с лечением. Подробности тут.

    Introduction

    In this article, you will see how we create a Scientific calculator using C#.

    C#

    C# is an object-oriented programming language, developed by Microsoft in 2000 to adopt the best features of Java and C++. It is used for a wide range of reasons, but its popularity lies in its use for the following tasks.

    1. Back End services
    2. Game Development
    3. Windows Application
    4.  Web Development

    Features of C#

    • Type-Safe C# type safe code can only access the memory location that it has permission to execute. Therefore it improves the security of the program.
    • Simple C# is a simple language in the sense that it provides a structured approach (to break the problem into parts), rich set of library functions, data types etc.
    • Rich Libraries C# provides a lot of inbuilt functions that make the development fast.
    • Object-Oriented C# is an object-oriented programming language. OOPs makes development and maintenance easier whereas in Procedure-oriented programming language it is not easy to manage if code grows as project size grow.

    What makes C# better?

    • It is a modern, general-purpose programming language
    • It is object-oriented.
    • It is component-oriented.
    • It is easy to learn.
    • It is a structured language.
    • It produces efficient programs.
    • It can be compiled on a variety of computer platforms.
    • It is a part of .Net Framework.

    .NET Framework

    The .Net framework is a revolutionary platform that helps you to write the following types of applications,

    • Windows applications
    • Web applications
    • Web services

    The .Net framework applications are multi-platform applications. The framework has been designed in such a way that it can be used from any of the following languages C#, C++, Visual Basic, Jscript, COBOL, etc. All these languages can access the framework as well as communicate with each other.

    The .Net framework consists of an enormous library of codes used by the client languages such as C#. Following are some of the components of the .Net framework

    • Common Language Runtime (CLR)
    • The .Net Framework Class Library
    • Common Language Specification
    • Common Type System
    • Metadata and Assemblies
    • Windows Forms
    • ASP.Net and ASP.Net AJAX
    • ADO.Net
    • Windows Workflow Foundation (WF)
    • Windows Presentation Foundation
    • Windows Communication Foundation (WCF)
    • LINQ

    What is a Calculator and why is it important?

    Calculators are simply a tool students use to help solve problems. Since they eliminate tedious computations and algebraic manipulations that discourage many students, calculators allow more students to solve problems and appreciate the power and value of mathematics in the world today.

    Nowadays, calculators in institutions are just as widely made use of as computers are. Due to the fact that its development virtually forty years back, the electronic calculator has evolved from a device that might only perform simple four-function procedures into one that may now likewise implement extremely technological algebraic emblematic manipulations quickly as well as accurately.

    calc 

    What is a Scientific calculator and why is it important?

    By definition, a scientific calculator is a calculator designed to help you calculate science, engineering, and mathematics problems. It has way more buttons than your standard calculator that just lets you do your four basic arithmetic operations of addition, subtraction, multiplication, and division.

    Uses

    All these extra buttons allow you to work with various kinds of numbers and problems such as these

    • Trigonometry problems
    • Scientific numbers that have a multiplication by 10 to a certain power.
    • Pi problems
    • Logarithm problems with base 10 and the natural base
    • Probability problems that use the factorial function

    You can now use your calculator to help you solve trigonometry problems involving sine, cosine, tangent, their inverses, and their hyperbolic functions. When working with trigonometric values, you can change the calculations between degrees, radians, and grads. Also, you now have access to a button for pi and Euler’s constant, e. There are also buttons that allow you to easily calculate exponents to the second, third, or any other power.

    When working with scientific numbers, there is an Exp button that lets you easily and quickly input scientific numbers.

    Engineering problems make use of exponents, logs, and scientific numbers.

    Also, all of these types of problems are usually longer expressions that involve several steps to solve by hand. But with the use of a scientific calculator, you can now input the whole expression, push the equals button, and the calculator will perform all the calculations you need in the right order. Yes, the scientific calculator computes your problems following the order of operations.

    scicalc 

    Special Buttons

    To help you write your equations, your scientific calculator has some special buttons.

    For scientific numbers, you have a special button that automatically adds the multiplication by 10 to a certain exponent. This button is the Exp button. You input your scientific number, then push the button, and then input your exponent value.

    exp 

    Also, for working with engineering problems, you can calculate a number to any exponent and you can take a number and find the square root, the third root, and any other root by using these buttons.

    square

    And of course, you have your trigonometric buttons.

    tri

    Implementation Using C#

    Design 

    calcC# 

    Toolboxes Used

    The Textbox

    The text box is for accepting input from the user as well as to display the output. It can handle string and numeric data but not images or pictures. String in a text box can be converted to numeric data by using the function Val(text). The label control is only for displaying a caption/title or to display an output.

    The Label

    The label can be used to provide instructions and guides to the user as well as to display the output. It is different from TextBox because it can only display static text, which means the user cannot change the text. Using the syntax Label.Text can display text and numeric data. You can change its text in the properties window or program it to change at runtime.

    The Button 

    The Button control represents a standard Windows button. It is generally used to generate a Click event by providing a handler for the Click event.

    Math Class in C#

    In C#, Math class comes under the System namespace. It is used to provide static methods and constants for logarithmic, trigonometric, and other useful mathematical functions. It is a static class and inherits the object class.

    Below is the list of Math functions used in this project 

    • Math.PI It represents the ratio of the circumference of a circle to its diameter, specified by the constant, PI(π). 
    • Math.Cos() Returns the cosine of the specified angle.
    • Math.Sin() Returns the sine of the specified angle.
    • Math.Tan() Returns the tangent of the specified angle. 
    • Math.Cosh() Returns the hyperbolic cosine of the specified angle. 
    • Math.Sinh(): Returns the hyperbolic sine of the specified angle. 
    • Math.Tanh() Returns the hyperbolic tangent of the specified angle. 
    • Math.Exp() Returns e raised to the power of a specific number. 
    • Math.Floor() Returns the largest integral value less than or equal to the specified number. 
    • Math.Pow() Returns a specified number raised to the specified power.
    • Math.Sqrt() Returns the square root of the specified number.
    • Math.Log() Returns the logarithm of a specified number. 
    • Math.Log10() Returns the base 10 logarithms of a specified number. 
    • Math.Ceiling(): Return the smallest integral value greater than or equal to the specified number.

    Code Implementation

    Button 0-9

    1. private void button1_Click(object sender, EventArgs e) {  
    2.     if (textBox.Text == “0” || isoptr) {  
    3.         textBox.Clear();  
    4.     }  
    5.     isoptr = false;  
    6.     Button button = (Button) sender;  
    7.     if (textBox.Text == “.”) {  
    8.         if (!textBox.Text.Contains(“.”)) {  
    9.             textBox.Text += button.Text;  
    10.         }  
    11.     } else textBox.Text += button.Text;  
    12.       
    13. }   

    Buttons Operators 

    1. private void button39_Click(object sender, EventArgs e) {  
    2.     switch (abbb) {  
    3.         case “+”  
    4.         textBox.Text = (firstdigit + double.Parse(textBox.Text)).ToString();  
    5.         break;  
    6.         case “-“  
    7.         textBox.Text = (firstdigit – double.Parse(textBox.Text)).ToString();  
    8.         break;  
    9.         case “*”  
    10.         textBox.Text = (firstdigit * double.Parse(textBox.Text)).ToString();  
    11.         break;  
    12.         case “/”  
    13.         textBox.Text = (firstdigit / double.Parse(textBox.Text)).ToString();  
    14.         break;  
    15.     }  
    16. }   

    Backspace button 

    1. private void button22_Click(object sender, EventArgs e) {  
    2.     int index = textBox.Text.Length;  
    3.     index–;  
    4.     textBox.Text = textBox.Text.Remove(index);  
    5.     if (textBox.Text == “”) {  
    6.         textBox.Text = “0”;  
    7.     }  
    8. }   

    Clear button 

    1.  private void button21_Click(object sender, EventArgs e)  
    2.  {  
    3.     textBox.Text = “0”;  
    4.  }  

    ± button

    1.  private void button23_Click(object sender, EventArgs e)  
    2.  {  
    3.     result = double.Parse(textBox.Text);  
    4.     result = result * -1;  
    5.     textBox.Text = result.ToString();  
    6.  }  

    Square root button

    1.  private void button11_Click(object sender, EventArgs e)  
    2.  {  
    3.     result = double.Parse(textBox.Text);  
    4.     result = Math.Sqrt(result);  
    5.    
    6.     textBox.Text = result.ToString();  
    7.  }  

    % button

    1.  private void button18_Click(object sender, EventArgs e)  
    2.  {  
    3.     result = double.Parse(textBox.Text);  
    4.     result = result / 100;  
    5.     textBox.Text = result.ToString();  
    6.  }  

    Ceil Button

    
    
    1.  private void button19_Click(object sender, EventArgs e)  
    2.  {  
    3.     result = double.Parse(textBox.Text);  
    4.     result = Math.Ceiling(result);  
    5.     textBox.Text = result.ToString();  
    6.  }  
    
    

    Floor Button

    1.  private void button20_Click(object sender, EventArgs e)  
    2.  {  
    3.     result = double.Parse(textBox.Text);  
    4.     result = Math.Floor(result);  
    5.     textBox.Text = result.ToString();  
    6.  }  

    Square Button

    1.  private void button12_Click(object sender, EventArgs e)  
    2.  {  
    3.     result = double.Parse(textBox.Text);  
    4.     result = Math.Pow(result,2);  
    5.     textBox.Text = result.ToString();  
    6.  }  

    Cube Button

    1.  private void button14_Click(object sender, EventArgs e)  
    2.  {  
    3.     result = double.Parse(textBox.Text);  
    4.     result = Math.Pow(result,3);  
    5.     textBox.Text = result.ToString();  
    6.  }  

    1/x Button

    1.  private void button14_Click(object sender, EventArgs e)  
    2.  {  
    3.     result = double.Parse(textBox.Text);  
    4.     result = 1/result;  
    5.     textBox.Text = result.ToString();  
    6.  }  

    MOD Button

    
    
    1.  private void button15_Click(object sender, EventArgs e)  
    2.  {  
    3.     result = double.Parse(textBox.Text);  
    4.     result = (firstdigit % double.Parse(textBox.Text));  
    5.     textBox.Text = result.ToString();  
    6.  }  
    
    

    Log Button

    1.  private void button6_Click(object sender, EventArgs e)  
    2.  {  
    3.     result = double.Parse(textBox.Text);  
    4.     result = Math.Log10(result);  
    5.     textBox.Text = result.ToString();  
    6.  }  

    Sin Button

    1.  private void button7_Click(object sender, EventArgs e)  
    2.  {  
    3.     result = double.Parse(textBox.Text);  
    4.     result = Math.Sin(result);  
    5.     textBox.Text = result.ToString();  
    6.  }  

    Cos Button

    
    
    1.  private void button8_Click(object sender, EventArgs e)  
    2.  {  
    3.     result = double.Parse(textBox.Text);  
    4.     result = Math.Cos(result);  
    5.     textBox.Text = result.ToString();  
    6.  }  
    
    

    Tan Button

    
    
    1.  private void button9_Click(object sender, EventArgs e)  
    2.  {  
    3.     result = double.Parse(textBox.Text);  
    4.     result = Math.Tan(result);  
    5.     textBox.Text = result.ToString();  
    6.  }  
    
    

    Pi Button

    1.  private void button10_Click(object sender, EventArgs e)  
    2.  {  
    3.    
    4.     result = Math.PI;  
    5.     textBox.Text = result.ToString();  
    6.  }  

    Exponential Button

    1.  private void button5_Click(object sender, EventArgs e)  
    2.  {  
    3.     result = double.Parse(textBox.Text);  
    4.     result = Math.Exp(result);  
    5.     textBox.Text = result.ToString();  
    6. }  

    TanH Button

    1.  private void button4_Click(object sender, EventArgs e)  
    2.  {  
    3.     result = double.Parse(textBox.Text);  
    4.     result = Math.Tanh(result);  
    5.     textBox.Text = result.ToString();  
    6.  }  

    CosH Button

    1.  private void button3_Click(object sender, EventArgs e)  
    2.  {  
    3.     result = double.Parse(textBox.Text);  
    4.     result = Math.Cosh(result);  
    5.     textBox.Text = result.ToString();  
    6.  }  

    SinH Button

    1.  private void button2_Click(object sender, EventArgs e)  
    2.  {  
    3.     result = double.Parse(textBox.Text);  
    4.     result = Math.Sinh(result);  
    5.     textBox.Text = result.ToString();  
    6.  }  

    OFF Button

    1.  private void button1_Click_1(object sender, EventArgs e)  
    2.  {  
    3.     Application.Exit();  
    4.  }  

    Natural Log x button

    1.  private void button17_Click(object sender, EventArgs e)  
    2.  {  
    3.     result = double.Parse(textBox.Text);  
    4.     result = Math.Log(result);  
    5.     textBox.Text = result.ToString();}  

    Output

    Here is the output in which I have performed basic multiplication and used the square root method.

    Multiplication

    Input

    5*5

    Expected output:

    25

    Multiplication 

    Square Root

    Input

    25

    Expected Output

    5

    sqrt

    Conclusion

    In this article, we learned how to make a Scientific calculator using C#.

    ITVDN Forum - сообщество разработчиков

    Завантаження

    Добавить комментарий