c语言中自定义函数计算x的n次方。
1、直接输出形式
#include <stdio.h>
int main(void) { int i, x, n; int tmp = 1; puts("please input the values of x and n."); printf("x = "); scanf("%d", &x); printf("n = "); scanf("%d", &n); for(i = 1; i <= n; i++) { tmp *= x; } printf("the result ls: %d\n", tmp); return 0; }
2、自定义函数,通用浮点型和整型
#include <stdio.h>
double power(double x, int n) { double tmp = 1.0; int i; for(i = 1; i <= n; i++) { tmp *= x; } return tmp; } int main(void) { double a; int b; puts("please input double a and int b."); printf("a = "); scanf("%lf", &a); printf("b = "); scanf("%d", &b); printf("result: %.2f\n", power(a, b)); return 0; }
3、
#include <stdio.h> double power(double x, int n) { double tmp = 1.0; while(n-- > 0) { tmp *= x; } return tmp; } int main(void) { double a; int b; puts("please input double a and int b."); printf("a = "); scanf("%lf", &a); printf("b = "); scanf("%d", &b); printf("result: %.2f\n", power(a, b)); return 0; }