C言語の例 - 数値のn乗を計算する

C言語の例

数値のn乗を計算します。例: 23ここで2は基数、3は指数です。

例 - whileを使用

#include <stdio.h> int main() { int base, exponent; long long result = 1; printf("基数:"); scanf("%d", &base); printf("指数:"); scanf("%d", &exponent); while (exponent != 0) { result *= base; --exponent; } printf("結果:%lld", result); return 0; }

実行結果:

基数: 2
指数: 3
结果:8

例 - pow()関数を使用

#include <stdio.h> #include <math.h> int main() { double base, exponent, result; printf("基数:"); scanf("%lf", &base); printf("指数:"); scanf("%lf", &exponent); // 計算結果 result = pow(base, exponent); printf("%.1lf^%.1lf = %.2lf", base, exponent, result); return 0; }

実行結果:

基数: 2
指数: 3
2.0^3.0 = 8.00

例 - 再帰

#include <stdio.h> int power(int n1, int n2); int main() { int base, powerRaised, result; printf("基数:"); scanf("%d",&base); printf("指数(正の整数):"); scanf("%d",&powerRaised); result = power(base, powerRaised); printf("%d^%d = %d", base, powerRaised, result); return 0; } int power(int base, int powerRaised) { if (powerRaised != 0) return (base*power(base, powerRaised-1)); else return 1; }

C言語の例

その他の拡張