在此示例中,您將學(xué)習(xí)計(jì)算數(shù)字的冪。
要理解此示例,您應(yīng)該了解以下C語言編程主題:
下面的程序從用戶那里獲取兩個(gè)整數(shù)(一個(gè)基數(shù)和一個(gè)指數(shù))并計(jì)算功效。
例如:在2 3的情況下
2是基數(shù)
3是指數(shù)
等同于 2*2*2
#include <stdio.h>
int main() {
int base, exp;
long long result = 1;
printf("輸入基數(shù): ");
scanf("%d", &base);
printf("輸入指數(shù): ");
scanf("%d", &exp);
while (exp != 0) {
result *= base;
--exp;
}
printf("冪 = %lld", result);
return 0;
}輸出結(jié)果
輸入基數(shù): 3 輸入指數(shù): 4 冪 = 81
上述技術(shù)僅在指數(shù)為正整數(shù)時(shí)有效。
如果您需要找到具有任何實(shí)數(shù)的指數(shù)的冪,可以使用pow()函數(shù)。
#include <math.h>
#include <stdio.h>
int main() {
double base, exp, result;
printf("輸入基數(shù): ");
scanf("%lf", &base);
printf("輸入指數(shù): ");
scanf("%lf", &exp);
//計(jì)算冪值
result = pow(base, exp);
printf("%.1lf^%.1lf = %.2lf", base, exp, result);
return 0;
}輸出結(jié)果
輸入基數(shù): 2.3 輸入指數(shù): 4.5 2.3^4.5 = 42.44