. Advertisement .
..3..
. Advertisement .
..4..
Math is the one thing that all programmers will have to deal with, sooner or later. You need it if you want to customize codes according to your needs. As you may know, a vital part of any math expression is the operator, as it tells the computer what to do.
That is why we figure knowing how to use exponent in C# will benefit you greatly. After all, the exponent operator is critical to the power raising of a number, which is staple in math.
Using Math.Pow() For Exponent In C#
While there is no official exponent operator in C#, we do have a quick solution, the Math.Pow() function. As you can see, it is a feature of the Math class, specializing in calculating the result of raising to the power a number according to another number.
Here is its syntax:
public static double Pow(double base, double power)
There are two input parameters, double base and double power. Both of them need to be double-precision floating-point in nature. The base variable is the number that needs to be raised to a power while the power variable specifies the exponent to raise the base value.
The returned value will be a number that has been raised to the power from the base.
Here is an example on how it works:
using System;
public class Program {
public static void Main() {
double a, b, c;
a = 2;
b = 4;
c = Math.Pow(a, b);
Console.WriteLine(c);
}
}
Output:
16
Special Cases For Return Of Math.Pow() For Exponent In C#
There are some special cases with specific returns for this function. If both base and power is NaN, the return should be NaN. When the power value is zero and the base value is anything but NaN, you have an output of 1.
Another unique case is when the base value is zero. In this case, the power value will determine the output. If it’s larger than zero, the output is zero. On the other hand, if it’s less than zero, the value reaches positive infinity.
There are some more cases that you can check here.
Exponent In C# Without Using Math.Pow()
If you don’t like to use Math.Pow(), you can also make a function on your own and call it whenever there is a need. Here is an example of how to do so:
public static double Pow(double base, int exp) {
double res = 1;
bool check = true;
if(exp<0) {
check = false;
exp = exp * -1;
}
for (int i = 1; i <= exp; i++) {
if (check)
res = res * base;
else
res /= base;
}
return res;
}
This function can be loaded as long as it’s specified before the function calling it. You should keep this in mind, as not specifying a function properly is one of the most common mistakes, like giving the wrong path format.
Conclusion
This article has shown you the way to work exponent in C#. You do need to remember that the Math.Pow() needs the C underlying runtime. Due to this nature, the valid input range does differ if you are using different operating architectures or systems.
If you find this article helpful, look forward to our next one.
Leave a comment