简体   繁体   中英

Execution time limit was exceeded c#, while using Math.Pow() in recursion

I am trying to print the power of number. but I am getting execution time exceeded error.

   using System;


public class Program
{

     public static void Power(int B,int C)
    {
        if(B == 1)
            return;
        double temp = Math.Pow(B,C);
        Console.WriteLine(temp);
        Power(B--,C);
    }

    public static void Main()
    {
        Console.WriteLine("Hello World");
        Power(4,2);
    }
}

I am getting this error.

Run-time exception (line -1): Execution time limit was exceeded

please help me understand the error.

change this line:

Power(B--,C);

To

Power(--B,C); 

or

B--;
Power(B,C);

It is because B-- sends the value of B not B-1 to the method, before subtracting 1. and this causes infinite loop, B stays the same.

您有B--传递B的当前值,然后减去1。而是写入--B。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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