c语言中函数的定义和调用(值传递,计算x的n次幂)
1、值传递,计算x的n次幂
#include <stdio.h>
double power(double x, int n)
{
int i;
double tmp = 1.0;
for (i = 1; i <= n; i++)
{
tmp *= x;
}
return tmp;
}
int main(void)
{
double a;
int b;
puts("please input the value of a and b.");
printf("a = "); scanf("%lf", &a);
printf("b = "); scanf("%d", &b);
printf("result = %.3f\n", power(a, b));
return 0;
}
↓
#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 the value of a and b.");
printf("a = "); scanf("%lf", &a);
printf("b = "); scanf("%d", &b);
printf("result = %.4f", power(a, b));
return 0;
}
↓
#include <stdio.h>
double power(double x, int n)
{
double tmp = 1.0;
for (n; n > 0; n--)
{
tmp *= x;
}
return tmp;
}
int main(void)
{
double a;
int b;
puts("please input the value of a and b.");
printf("a = "); scanf("%lf", &a);
printf("b = "); scanf("%d", &b);
printf("result = %.3f", power(a, b));
return 0;
}