自定义函数的运用及练习题

img

img


自定义函数return到哪?
顺便能不能看看这道题写的对不对

这样呢
#include<stdio.h>
#include<math.h>
double P(double x,int n)
{
int b,c;
double sum=1,a=1;
if(n==0);
else
{
for(b=1;b<=n;b++)
{
for(c=1;c<=b;c++)
{
a = x*a;
}
sum = sum+a;
a=1;
}
}
return sum;
}
int main(void)
{
int n;
double x,sum=1;
scanf("%lf%d",&x,&n);
sum=P(x,n);
printf("%f\n",sum);
return 0;
}

p函数应该return t;
不是return double

p函数是把 t 返回给调用p函数的地方
调用p函数是 SUM = P(2,0); 也就是把 t 返回赋值给 SUM
另外,你代码也不对, 乘方应该直接用pow()函数,不用循环计算乘方
你题目的解答代码如下:

#include<stdio.h>
#include<math.h>

double P(double x,int n)
{
    double t = 1;
    int i;
    for(i=1;i<=n;i++) {
        t += pow(x,i);
    }
    return t;
}
int main()
{
    double x,SUM;
    int n;
    scanf("%lf%d",&x,&n);
    SUM = P(x,n);
    printf("%lf",SUM);
    return 0;
}

img

如有帮助,望采纳!谢谢!

函数return到哪
能顺便看看题怎么写吗