Maison  >  Article  >  développement back-end  >  Fonctions mathématiques en C#

Fonctions mathématiques en C#

王林
王林original
2024-09-03 15:14:05231parcourir

La bibliothèque Math en C# fournit aux développeurs diverses fonctions et propriétés générales, trigonométriques, statistiques et logarithmiques en mathématiques. C'est une bibliothèque prête à l'emploi, plug and play. La bibliothèque hérite de la classe Object, la classe super parent en C#. Il réside dans l'espace de noms Système.

Remarque : Une chose très importante à garder à l'esprit est que les propriétés et les méthodes de la classe Math sont toutes statiques, ce qui signifie que vous n'avez pas besoin de créer un objet de la classe Math pour les invoquer.

Propriétés mathématiques C#

Regardons les différentes propriétés mathématiques de la bibliothèque Math.

1. E4

E est la base logarithmique, spécifiée par la petite lettre « e » dans les équations mathématiques. Cette propriété statique contient la valeur de la base logarithmique naturelle.

Code :

using System;
public class Program
{
public static void Main()
{
Console.WriteLine("The value of logarithmic base E is " + Math.E);
}
}

Sortie :

Fonctions mathématiques en C#

2. PI

Pi, communément écrit sous le symbole p, est le rapport entre la circonférence du cercle et le diamètre (environ 3,14). Cette constante statique détient la valeur de p.

Code :

using System;
public class Program
{
public static void Main()
{
Console.WriteLine("The value of PI is " + Math.PI);
}
}

Sortie :

Fonctions mathématiques en C#

Fonctions mathématiques C#

Regardons les différentes fonctions mathématiques de la bibliothèque C# Math disponibles à notre disposition :

1. Fonction Abs-Absolue

Renvoie la valeur absolue d'un nombre donné (entier, décimal, virgule flottante, etc.). La valeur absolue de tout nombre est la valeur décimale maximale possible supérieure ou égale à 0 mais inférieure ou égale au nombre lui-même.

Code :

using System;
public class Program
{
public static void Main()
{
int num1 = 231;
double num2 = -1.23456789;
Console.WriteLine("The absolute value of {0} is {1} ", num1,  Math.Abs(num1));
Console.WriteLine("The absolute value of {0} is {1} ", num2,  Math.Abs(num2));
}
}

Sortie :

Fonctions mathématiques en C#

2. BigMul-Grande Multiplication

Cette fonction renvoie le résultat complet de la multiplication de deux très grands nombres entiers. Il prend deux entiers de 32 bits et renvoie un résultat de multiplication de 64 bits.

Code :

using System;
public class Program
{
public static void Main()
{
int num1 = Int32.MaxValue;
Console.WriteLine("Multiplication of {0}x{0} without Math function - {1}",num1, num1*num1);
Console.WriteLine("Multiplication of {0}x{0} by Math BigMul function - {1}",num1, Math.BigMul(num1, num1));
}
}

Sortie :

Fonctions mathématiques en C#

3. Sol et Plafond

Les fonctions floor() et plafond() renvoient les valeurs plancher et plafond d'un nombre spécifié. La valeur plancher de tout nombre est le plus grand entier inférieur ou égal au nombre lui-même. La valeur plafond de tout nombre est le plus petit entier supérieur ou égal au nombre lui-même.

Code :

using System;
public class Program
{
public static void Main()
{
double num1 = 548.65;
Console.WriteLine("Floor value of {0} is {1}", num1, Math.Floor(num1));
Console.WriteLine("Ceil value of {0} is {1}", num1, Math.Ceiling(num1));
}
}

Sortie :

Fonctions mathématiques en C#

4. Péché, cos et bronzage

Ces fonctions trigonométriques fournissent la valeur sinus, cosinus et tangente de l'angle spécifié.

Code :

using System;
public class Program
{
public static void Main()
{
double angle = 120.5;
Console.WriteLine("Sine value of {0} is {1}", angle, Math.Sin(angle));
Console.WriteLine("Cosine value of {0} is {1}", angle,Math.Cos(angle));
Console.WriteLine("Tangent value of {0} is {1}", angle, Math.Tan(angle));
}
}

Sortie :

Fonctions mathématiques en C#

5. Sinh, Cosh et Tanh–Hyperbole

Ces fonctions trigonométriques fournissent la valeur du sinus hyperbolique, du cosinus et de la tangente de l'angle spécifié.

Code :

using System;
public class Program
{
public static void Main()
{
double angle = 120.5;
Console.WriteLine("Hyperbolic Sine value of {0} is {1}", angle, Math.Sinh(angle));
Console.WriteLine("Hyperbolic Cosine value of {0} is {1}", angle, Math.Cosh(angle));
Console.WriteLine("Hyperbolic Tangent value of {0} is {1}", angle,Math.Tanh(angle));
}
}

Sortie :

Fonctions mathématiques en C#

6. Asin, Acos et Atan

Ces fonctions trigonométriques renvoient l'angle auquel le nombre spécifié est la valeur sinus, cosinus ou tangente.

Code :

using System;
public class Program
{
public static void Main()
{
double value = 1;
Console.WriteLine("The angle of sin({0}) is {1}", value, Math.Asin(value));
Console.WriteLine("The angle of cos({0}) is {1}", value, Math.Acos(value));
Console.WriteLine("The angle of tan({0}) is {1}", value, Math.Atan(value));
}
}

Sortie :

Fonctions mathématiques en C#

7. DivRem–Division et reste

Cette fonction calcule le résultat d'une division de deux entiers. Le résultat n'est pas renvoyé sous forme de valeur fractionnaire. Au lieu de cela, le quotient est renvoyé comme valeur de retour de la fonction et le reste comme paramètre de sortie.

Code :

using System;
public class Program
{
public static void Main()
{
int divisor = 8;
int dividend = 45;
int remainder = 0;
int quotient = Math.DivRem(dividend, divisor, out remainder);
Console.WriteLine("{0} divided by {1} results in {2} as the quotient and {3} as the remainder.", dividend, divisor, quotient, remainder);
}
}

Sortie :

Fonctions mathématiques en C#

8. Exp-Exponentiel

La fonction exp renvoie e à la puissance du nombre spécifié.

Code :

using System;
public class Program
{
public static void Main()
{
int power = 4;
Console.WriteLine("{0} to the power of {1} is {2}.", Math.E, power, Math.Exp(power));
}
}

Sortie :

Fonctions mathématiques en C#

9. Log, Log2 et Log10-Logarithme

La fonction log renvoie le logarithme d'un nombre spécifié dans une base spécifiée. Si aucune base n'est spécifiée, la base par défaut est e, ce qui donne le logarithme népérien.

Remarque : Log2 a été introduit dans .Net Core. Cette méthode n'est pas disponible dans le .Net Framework.

Code :

using System;
public class Program
{
public static void Main()
{
double num1 = 4.5;
int new_base = 12;
Console.WriteLine("Log({0}) to the base 'e' is {1}.", num1, Math.Log(num1));
Console.WriteLine("Log({0}) to the base 10 is {1}.", num1,Math.Log10(num1));
Console.WriteLine("Log({0}) to the base 2 is {1}.", num1,Math.Log(num1, 2));
Console.WriteLine("Log({0}) to the base {1} is {2}.", num1,new_base, Math.Log(num1, new_base));
}
}

Sortie :

Fonctions mathématiques en C#

10. Min et Max

Ces fonctions comparent les deux nombres fournis et renvoient le plus petit nombre ou le plus grand nombre des deux.

Code :

using System;
public class Program
{
public static void Main()
{
double num1 = 4.5;
double num2 = -3.4;
int num3 = 981;
int num4 = 123;
Console.WriteLine("Minimum of {0} and {1} is {2}.", num1, num2,Math.Min(num1, num2));
Console.WriteLine("Maximum of {0} and {1} is {2}.", num1, num2,Math.Max(num1, num2));
Console.WriteLine("Minimum of {0} and {1} is {2}.", num3, num4,Math.Min(num3, num4));
Console.WriteLine("Maximum of {0} and {1} is {2}.", num3, num4,Math.Max(num3, num4));
}
}

Sortie :

Fonctions mathématiques en C#

11. Pow-Power

The pow() function returns the specified number to the specified power.

Code:

using System;
public class Program
{
public static void Main()
{
int num1 = 11;
double num2 = 3.4;
Console.WriteLine("{0} to the power {1} is {2}.", num1, num2, Math.Pow(num1, num2));
Console.WriteLine("The cube of {0} is {1}.", num1, Math.Pow(num1, 3));
}
}

Output:

Fonctions mathématiques en C#

12. Round

The round() function, as the name suggests, rounds the specified number to the nearest integer or specified decimal places after the integer.

There are a few important variations of round() function. It takes either two or three arguments.

  1. The first argument is the number to be rounded.
  2. The second argument is the number of digits after the decimal point. If this is not specified, the number is rounded to the nearest integer.
  3. The third argument is the mode of rounding. This is an enumeration of two values derived accessed from the enum MidpointRounding.

The two modes are:

  • AwayFromZero: When a number falls halfway between two numbers, it is rounded to the nearest number which is farther from zero.
  • ToEven: When a number falls halfway between two numbers, it is rounded to the nearest even number.

If not specified, the mode AwayFromZero is the default mode.

Code:

using System;
public class Program
{
public static void Main()
{
double num1 = 2.45;
double num2 = 24.5;
Console.WriteLine("{0} rounded to the nearest integer is {1}", num1, Math.Round(num1));
Console.WriteLine("{0} rounded to the nearest single-point decimal is {1}", num1, Math.Round(num1, 1));
Console.WriteLine("{0} rounded to the nearest single-point decimal away from zero is {1}", num1, Math.Round(num1, 1, MidpointRounding.AwayFromZero));
Console.WriteLine("{0} rounded to the nearest single-point decimal to even is {1}", num1, Math.Round(num1, 1, MidpointRounding.ToEven));
Console.WriteLine("\n{0} rounded to the nearest integer away from zero is {1}", num2, Math.Round(num2, MidpointRounding.AwayFromZero));
Console.WriteLine("{0} rounded to the nearest integer to even is {1}", num2, Math.Round(num2, MidpointRounding.ToEven));
}
}

Output:

Fonctions mathématiques en C#

13. Sqrt-Square Root

This function returns the square root of the given number.

Code:

using System;
public class Program
{
public static void Main()
{
int num1 = 196;
double num2 = 404.1;
Console.WriteLine("Square root of {0} is {1}.", num1,Math.Sqrt(num1));
Console.WriteLine("Square root of {0} is {1}.", num2, Math.Sqrt(num2));
}
}

Output:

Fonctions mathématiques en C#

14. Truncate

The truncate function returns an integral part of the specified number. So, in simple terms, it discards anything after the decimal point and returns everything before the decimal point.

Note: Note that this is different from Round function. The round function returns an integer nearest to the number. It may be an integer greater than the number itself. Whereas, Truncate function would always return the integer part of the number as is. E.g. – Round(4.9) results in 5. Truncate(4.9) results in 4.

Code:

using System;
public class Program
{
public static void Main()
{
double num1 = 404.92;
Console.WriteLine("Truncated value of {0} is {1}.", num1, Math.Truncate(num1));
Console.WriteLine("Rounded-off value of {0} is {1}.", num1, Math.Round(num1));
}
}

Output:

Fonctions mathématiques en C#

Conclusion

This article covered almost all the mathematical functions provided in the C# Math library. This library proves to be very useful due to the plug-n-play mathematical properties and functions, thereby making development easier.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Article précédent:Fonctions de chaîne C#Article suivant:Fonctions de chaîne C#