C语言有关函数的问题

来源:百度知道 编辑:UC知道 时间:2024/05/25 01:23:08
写一个函数power(double x,int n),其返回值是x^n
#include<stdio.h>
double power(double x,int n)
{double a;
int t;
for(a=1,t=1;t<=n;t++)
a=a*x;
return a;
}
void main()
{
double x;
int n;
scanf("%f,%d",&x,&n);
printf("x^n=%f\n",power(x,n));
}

为何我写的程序输入x,n的值答案却不对呢?
请赐教!~

你的程序中:
scanf("%f,%d",&x,&n);
应改为
scanf("%lf,%d",&x,&n);

最好将
printf("x^n=%f\n",power(x,n));
改为
printf("x^n=%lf\n",power(x,n));

*************************************

非递归函数:

double power(double x,int n)
{
double a=x;
while (--n>0) a*=x;
return a;
}

递归函数:

double power(double x,int n)
{
if (n>1) return power(x,n-1)*x;
else return x;
}

这个是开方啊,不是幂

double power(double x,int n)
{
int i = 0;
double result=1;
for(i;i<n;i++)
result*=x;
return result;
}