第六版C primer plus9.11的第八题

weixin_40993974 2017-11-24 05:00:03
输入n 和exp,设计一个函数能够返回n的exp次方的值,exp可以是正数,负数和0,题目不难,主要是我的返回值不知道怎么搞的一直是0.
#include <stdio.h>

double power(double n,int p);
int main()
{
double x,ans;
int exp;
printf("now input a number and the integer power:\n ");
printf("Enter 'q' to quit.\n");
while(scanf("%lf %d",&x,&exp)==2)
{
ans=power(x,exp);
printf("%lf的%d次幂的值为%d\n",x,exp,ans);
printf("now input a number and the integer power:\n ");
printf("Enter 'q' to quit.\n");
}
printf("bye!\n");
}
double power(double n,int p)
{
int i;
double sum=1;
if(n==0&&p==0)
{
printf("%lf的%d次幂未定义,因此把值处理为%d\n",n,p,1);
sum=1.0;
}
else if(n==0)
sum=0;
else if(n!=0&&p>0)
{
for(i=0;i<p;i++)
sum*=n;
}
else if(n!=0&&p<0)
{
for(i=0;i<(-p);i++)
sum*=1/n;
}
return sum;
}
...全文
262 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
hongss 2017-11-25
  • 打赏
  • 举报
回复
怎么不能加红呢。。。郁闷ing
int main()
{
    double x,ans;
    int exp;
    printf("now input a number and the integer power:\n ");
    printf("Enter 'q' to quit.\n");
    while(scanf("%lf %d",&x,&exp)==2)
    {
    ans=power(x,exp);
//    printf("%lf的%d次幂的值为%d\n",x,exp,ans);    输出参数设置有问题,改成下边的就好了
    printf("%lf的%d次幂的值为%f\n",x,exp,ans);
    printf("now input a number and the integer power:\n ");
    printf("Enter 'q' to quit.\n");
    }
    printf("bye!\n");
}
hongss 2017-11-25
  • 打赏
  • 举报
回复
一点小小错误
int main()
{
    double x,ans;
    int exp;
    printf("now input a number and the integer power:\n ");
    printf("Enter 'q' to quit.\n");
    while(scanf("%lf %d",&x,&exp)==2)
    {
    ans=power(x,exp);
    printf("%lf的%d次幂的值为%f\n",x,exp,ans);
    printf("now input a number and the integer power:\n ");
    printf("Enter 'q' to quit.\n");
    }
    printf("bye!\n");
}
weixin_40993974 2017-11-25
  • 打赏
  • 举报
回复
引用 3楼hongss 的回复:
怎么不能加红呢。。。郁闷ing
int main()
{
    double x,ans;
    int exp;
    printf("now input a number and the integer power:\n ");
    printf("Enter 'q' to quit.\n");
    while(scanf("%lf %d",&x,&exp)==2)
    {
    ans=power(x,exp);
//    printf("%lf的%d次幂的值为%d\n",x,exp,ans);    输出参数设置有问题,改成下边的就好了
    printf("%lf的%d次幂的值为%f\n",x,exp,ans);
    printf("now input a number and the integer power:\n ");
    printf("Enter 'q' to quit.\n");
    }
    printf("bye!\n");
}
哈哈哈这个真的没看出来 666谢谢啦
ooolinux 2017-11-24
  • 打赏
  • 举报
回复
单步调试一下,看看sum变量值的变化。

13,825

社区成员

发帖
与我相关
我的任务
社区描述
C++ Builder相关内容讨论区
社区管理员
  • 基础类社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧