简体   繁体   English

数的负指数

[英]Negative exponent of a number

I made this program to find the power of any number using recursion and it works, but also I need to find negative power of the number, for example, I have the base = 2 and the exponent = -3 so the result = 0.125, what should I do?我制作了这个程序来使用递归找到任何数字的幂并且它有效,但我还需要找到数字的负幂,例如,我有底数 = 2 和指数 = -3 所以结果 = 0.125,我应该怎么办?

public static int power(int x, int n )
        {
            if (n < 0)
            {
                Console.WriteLine("invalid");
                return 0;
            }
            else if (n == 1)
            {
                return x;
            }
            else if (n == 0)
            {
                return 1;
            }
            else
            {
                return x * power(x, n - 1);
            }
        }

        static void Main(string[] args)
        {
            Console.Write("enter the base: ");
            int x = int.Parse(Console.ReadLine());
            Console.Write("enter the power:");
            int n = int.Parse(Console.ReadLine());
            int z = power(x, n);
            Console.WriteLine(z);
        }

Since the result of raising a number to a negative power is just 1 divided by the number raised to the non-negative power, you can change you method like so (note that we also need to return a double type, since we're dealing with fractional values):由于将数字提升到负幂的结果只是1除以提升到非负幂的数字,因此您可以像这样更改您的方法(请注意,我们还需要返回一个double类型,因为我们正在处理带小数值):

public static double power(int x, int n)
{
    if (n < 0) return 1 / power(x, -n);  // recursive call with '-n' for negative powers
    if (n == 0) return 1;
    if (n == 1) return x;
    return x * power(x, n - 1);
}

Now it works with negative numbers:现在它适用于负数:

public static void Main(string[] args)
{
    Console.WriteLine(power(2, -3));
    GetKeyFromUser("\nDone! Press any key to exit...");
}

Output Output

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM