使用 C# 中的遞迴查詢數字的冪
要查詢數字的冪,首先設定數字和冪 -
int n = 15; int p = 2;
現在建立一個方法並傳遞這些值 -
static long power(int n, int p) {
if (p != 0) {
return (n * power(n, p - 1));
}
return 1;
}
上面,遞迴呼叫為我們提供了結果 -
n * power(n, p - 1)
以下是獲取數字冪的完整程式碼 -
示例
using System;
using System.IO;
public class Demo {
public static void Main(string[] args) {
int n = 15;
int p = 2;
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;
}
}輸出
225
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP