如何使用C#计算三的幂?
对于3的幂,将幂设置为3并应用递归代码,如以下代码段所示-
if (p!=0) {
return (n * power(n, p - 1));
}假设数字为5,则迭代次数为-
power(5, 3 - 1)); // 25 power (5,2-1): // 5
上面将返回5*25,即125,如下所示-
示例
using System;
using System.IO;
public class Demo {
public static void Main(string[] args) {
int n = 5;
int p = 3;
long res;
res = power(n, p);
Console.WriteLine(res);
}
static long power (int n, int p) {
if (p!=0) {
return (n * power(n, p - 1));
}
return 1;
}
}输出结果
125