c语⾔中⾃定义函数计算x的n次⽅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);
return0;
}
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));
return0;
}自定义函数怎么用c语言
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)); return0;
}