如何使用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
热门推荐
10 广西考试祝福语结婚简短
11 猪年祝福语简短小孩
12 元旦祝福语送长辈简短
13 恭喜二宝祝福语简短
14 祝福语暖心话简短
15 国庆中秋祝福语简短兄弟
16 朋友订婚的祝福语简短
17 送弟弟中秋祝福语简短
18 爱生日祝福语简短独特