Como fazer conta de raiz quadrada na visual studio

Boas, Após as dicas dos utilizadores decidi melhorar o meu codigo C# da calculadora. Penso que esteja mais simples mas tenho um pequeno problema na Raiz quadrada pois tento fazer a conta e o resultado dá-me sempre 0.

private void btn_raiz_Click(object sender, RoutedEventArgs e) { resutado = Convert.ToSingle(Math.Sqrt(primeiro)); janela.Text = resutado.ToString(); }

2

. Visual Basic NET é uma linguagem de programação de computadores orientada a objetos implementado em NET Framework da Microsoft. . A linguagem fornece um conjunto básico de operadores aritméticos com o qual você pode realizar cálculos simples dentro de seu programa , como adição , subtração, multiplicação ou divisão. No entanto, a fim de realizar operações mais complexas, tais como raízes quadradas , você pode precisar aplicar funções na classe System.Math do NET Framework . . Instruções
1

Declare uma variável que servirá como a resposta à sua operação de raiz quadrada como um tipo duplo igual ao operador Math.Sqrt usando o seguinte formato - Dim MySqrt As Double = Math.Sqrt (4).
2

Substitua o número para o qual você deseja encontrar a raiz quadrada do número 4 no código.
3

Salvar e compilar seu código. Seu programa agora irá conter uma variável chamada MySqrt igual à raiz quadrada do número especificado , que pode ser a saída para o console ou usar para realizar outras operações matemáticas.

Como fazer conta de raiz quadrada na visual studio
C# - Simplificando a raiz quadrada

Como fazer conta de raiz quadrada na visual studio
Hoje vamos recordar alguns conceitos sobre matemática e  brincar com simplificação de radicais usando a linguagem C#.

Vamos começar relembrando alguns conceitos. Abaixo temos a expressão que representa um único número real x que elevado ao índice b resulta o número a :

Como fazer conta de raiz quadrada na visual studio

Como fazer conta de raiz quadrada na visual studio

A origem do símbolo usado para representar uma raiz é bastante especulativo.

Algumas fontes dizem que o símbolo foi usado pela primeira vez pelos árabes, que o primeiro uso foi de Al-Qalasadi (1421-1486), e que o símbolo vem da letra árabe ?, a primeira letra da palavra "Jadhir".( http://pt.wikipedia.org/wiki/)

Como fazer conta de raiz quadrada na visual studio

Vamos criar um programa na linguagem C# que se propõe a realizar a simplificação da raiz quadrada de qualquer número inteiro.

Abra o Visual C# 2010 Express Edition ou o Visual Studio Community mais recente e no menu File clique em New Project e escolha o template Windows Forms Application informando o nome SimplificarRaizQuadrada;

A seguir inclua no formulário form1.cs os seguintes controles:

  • Label
  • Button
  • PictureBox
  • LinkLabel

Conforme o leiaute abaixo:

Como fazer conta de raiz quadrada na visual studio

No evento Click do botão de comando Simplificar (btnSimplificar) vamos incluir o código abaixo:

private void btnSimplificar_Click(object sender, EventArgs e) { //Obtém o valor do radicando informado pelo usuário double valorRadicando = double.Parse(txtRadicando.Text); //verifica se o numero é um quadrado perfeito if (!IsDecimal(Math.Sqrt(valorRadicando))) { txtResultado1.Text = Math.Sqrt(valorRadicando).ToString(); txtResultado2.Text = "-"; return; } //verifica por inteiros cujo valor do quadrado é um múltiplo do valor informado double tQuadrado = 0; for (int i = (int)Math.Floor(Math.Sqrt(valorRadicando)); i >= 2; i--) { tQuadrado = valorRadicando / (double)(i * i); if (!IsDecimal(tQuadrado)) { txtResultado1.Text = i.ToString(); txtResultado2.Text = (valorRadicando / (i * i)).ToString(); return; } } txtResultado1.Text = "-"; txtResultado2.Text = "-"; }

Vamos entender o código...

1- Iniciamos convertendo o valor informado pelo usuário para o radicando para double:

double valorRadicando = double.Parse(txtRadicando.Text);

2- Verificamos a seguir se o número possui um quadrado perfeito. Neste caso apresentamos o resultado:

if (!IsDecimal(Math.Sqrt(valorRadicando))) {

    txtResultado1.Text = Math.Sqrt(valorRadicando).ToString();

    txtResultado2.Text = "-";     return;

}

Nota: A função IsDecimal é usada para permitir somente valores inteiros e neste caso verifica se o número obtido é um número inteiro.

private Boolean IsDecimal(double valorRadicando) { return (int)valorRadicando != valorRadicando; }

Outro maneira de calcular o quadrado perfeito é obtida usando este código:(No caso para número inteiros)

public static bool Quadrado_Perfeito(int n) { if (n < 0) return false; long tst = (int)(Math.Sqrt(n) + 0.5); return tst * tst == n; }

3- Iniciamos com o valor inteiro da raiz quadrada do número iniciamos o loop :

for (int i = (int)Math.Floor(Math.Sqrt(valorRadicando)); i >= 2; i--){}

A seguir testamos cada número para ver se ele é um múltiplo do número original. Se for, então você calculamos a raiz quadrada do mesmo e deixamos o restante no interior do sinal de raiz quadrada.

for (int i = (int)Math.Floor(Math.Sqrt(valorRadicando)); i >= 2; i--) {tQuadrado = valorRadicando / (double)(i * i);   if (!IsDecimal(tQuadrado))   {    txtResultado1.Text = i.ToString();    txtResultado2.Text = (valorRadicando / (i * i)).ToString();

   return;

  }

}

Executando o projeto e realizando um cálculo como exemplo obtemos seguinte resultado:

Como fazer conta de raiz quadrada na visual studio

O algoritmo usado não é necessariamente o mais otimizado nem esta sujeito a falhas, visto que eu não realizei testes mais apurados. Se você encontrar um algoritmo melhor ou encontrar erros me avise.

Pegue o projeto completo aqui:

Como fazer conta de raiz quadrada na visual studio
SimplificarRaiz.zip
Como fazer conta de raiz quadrada na visual studio
QuadradosPerfeitos.zip

João 14:27

Deixo-vos a paz, a minha paz vos dou; eu não vo-la dou como o mundo a dá. Não se turbe o vosso coração, nem se atemorize.
 

Como fazer conta de raiz quadrada na visual studio

Referências:

José Carlos Macoratti

Returns a Double specifying the square root of a number.

Syntax

Sqr(number)

The required number argument is a Double or any valid numeric expression greater than or equal to zero.

Example

This example uses the Sqr function to calculate the square root of a number.

Dim MySqr MySqr = Sqr(4) ' Returns 2. MySqr = Sqr(23) ' Returns 4.79583152331272. MySqr = Sqr(0) ' Returns 0. MySqr = Sqr(-4) ' Generates a run-time error.

See also

  • Functions (Visual Basic for Applications)

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

The methods of the System.Math class provide trigonometric, logarithmic, and other common mathematical functions.

The following table lists methods of the System.Math class. You can use these in a Visual Basic program:

.NET method Description
Abs Returns the absolute value of a number.
Acos Returns the angle whose cosine is the specified number.
Asin Returns the angle whose sine is the specified number.
Atan Returns the angle whose tangent is the specified number.
Atan2 Returns the angle whose tangent is the quotient of two specified numbers.
BigMul Returns the full product of two 32-bit numbers.
Ceiling Returns the smallest integral value that's greater than or equal to the specified Decimal or Double.
Cos Returns the cosine of the specified angle.
Cosh Returns the hyperbolic cosine of the specified angle.
DivRem Returns the quotient of two 32-bit or 64-bit signed integers, and also returns the remainder in an output parameter.
Exp Returns e (the base of natural logarithms) raised to the specified power.
Floor Returns the largest integer that's less than or equal to the specified Decimal or Double number.
IEEERemainder Returns the remainder that results from the division of a specified number by another specified number.
Log Returns the natural (base e) logarithm of a specified number or the logarithm of a specified number in a specified base.
Log10 Returns the base 10 logarithm of a specified number.
Max Returns the larger of two numbers.
Min Returns the smaller of two numbers.
Pow Returns a specified number raised to the specified power.
Round Returns a Decimal or Double value rounded to the nearest integral value or to a specified number of fractional digits.
Sign Returns an Integer value indicating the sign of a number.
Sin Returns the sine of the specified angle.
Sinh Returns the hyperbolic sine of the specified angle.
Sqrt Returns the square root of a specified number.
Tan Returns the tangent of the specified angle.
Tanh Returns the hyperbolic tangent of the specified angle.
Truncate Calculates the integral part of a specified Decimal or Double number.

The following table lists methods of the System.Math class that don't exist in .NET Framework but are added in .NET Standard or .NET Core:

.NET method Description Available in
Acosh Returns the angle whose hyperbolic cosine is the specified number. Starting with .NET Core 2.1 and .NET Standard 2.1
Asinh Returns the angle whose hyperbolic sine is the specified number. Starting with .NET Core 2.1 and .NET Standard 2.1
Atanh Returns the angle whose hyperbolic tangent is the specified number. Starting with .NET Core 2.1 and .NET Standard 2.1
BitDecrement Returns the next smallest value that compares less than x. Starting with .NET Core 3.0
BitIncrement Returns the next largest value that compares greater than x. Starting with .NET Core 3.0
Cbrt Returns the cube root of a specified number. Starting with .NET Core 2.1 and .NET Standard 2.1
Clamp Returns value clamped to the inclusive range of min and max. Starting with .NET Core 2.0 and .NET Standard 2.1
CopySign Returns a value with the magnitude of x and the sign of y. Starting with .NET Core 3.0
FusedMultiplyAdd Returns (x * y) + z, rounded as one ternary operation. Starting with .NET Core 3.0
ILogB Returns the base 2 integer logarithm of a specified number. Starting with .NET Core 3.0
Log2 Returns the base 2 logarithm of a specified number. Starting with .NET Core 3.0
MaxMagnitude Returns the larger magnitude of two double-precision floating-point numbers. Starting with .NET Core 3.0
MinMagnitude Returns the smaller magnitude of two double-precision floating-point numbers. Starting with .NET Core 3.0
ScaleB Returns x * 2^n computed efficiently. Starting with .NET Core 3.0

To use these functions without qualification, import the System.Math namespace into your project by adding the following code to the top of your source file:

Imports System.Math

Example - Abs

This example uses the Abs method of the Math class to compute the absolute value of a number.

Dim x As Double = Math.Abs(50.3) Dim y As Double = Math.Abs(-50.3) Console.WriteLine(x) Console.WriteLine(y) ' This example produces the following output: ' 50.3 ' 50.3

Example - Atan

This example uses the Atan method of the Math class to calculate the value of pi.

Public Function GetPi() As Double ' Calculate the value of pi. Return 4.0 * Math.Atan(1.0) End Function

Note

The System.Math class contains Math.PI constant field. You can use it rather than calculating it.

Example - Cos

This example uses the Cos method of the Math class to return the cosine of an angle.

Public Function Sec(angle As Double) As Double ' Calculate the secant of angle, in radians. Return 1.0 / Math.Cos(angle) End Function

Example - Exp

This example uses the Exp method of the Math class to return e raised to a power.

Public Function Sinh(angle As Double) As Double ' Calculate hyperbolic sine of an angle, in radians. Return (Math.Exp(angle) - Math.Exp(-angle)) / 2.0 End Function

Example - Log

This example uses the Log method of the Math class to return the natural logarithm of a number.

Public Function Asinh(value As Double) As Double ' Calculate inverse hyperbolic sine, in radians. Return Math.Log(value + Math.Sqrt(value * value + 1.0)) End Function

Example - Round

This example uses the Round method of the Math class to round a number to the nearest integer.

Dim myVar2 As Double = Math.Round(2.8) Console.WriteLine(myVar2) ' The code produces the following output: ' 3

Example - Sign

This example uses the Sign method of the Math class to determine the sign of a number.

Dim mySign1 As Integer = Math.Sign(12) Dim mySign2 As Integer = Math.Sign(-2.4) Dim mySign3 As Integer = Math.Sign(0) Console.WriteLine(mySign1) Console.WriteLine(mySign2) Console.WriteLine(mySign3) ' The code produces the following output: ' 1 ' -1 ' 0

Example - Sin

This example uses the Sin method of the Math class to return the sine of an angle.

Public Function Csc(angle As Double) As Double ' Calculate cosecant of an angle, in radians. Return 1.0 / Math.Sin(angle) End Function

Example - Sqrt

This example uses the Sqrt method of the Math class to calculate the square root of a number.

Dim mySqrt1 As Double = Math.Sqrt(4) Dim mySqrt2 As Double = Math.Sqrt(23) Dim mySqrt3 As Double = Math.Sqrt(0) Dim mySqrt4 As Double = Math.Sqrt(-4) Console.WriteLine(mySqrt1) Console.WriteLine(mySqrt2) Console.WriteLine(mySqrt3) Console.WriteLine(mySqrt4) ' The code produces the following output: ' 2 ' 4.79583152331272 ' 0 ' NaN

Example - Tan

This example uses the Tan method of the Math class to return the tangent of an angle.

Public Function Ctan(angle As Double) As Double ' Calculate cotangent of an angle, in radians. Return 1.0 / Math.Tan(angle) End Function

See also

  • Rnd
  • Randomize
  • NaN
  • Derived Math Functions
  • Arithmetic Operators