正在计算n!和x ^ n并进行计算[关闭]

问题描述 投票:0回答:1
编写C程序以计算(x ^ n)/(n!),其中x为浮点数,n为大于或等于零的整数。

我编码了以下内容:

#include<stdio.h> #include<math.h> void main() { float x,p; int i,n,f=1; printf("Enter the value of x,n\n"); scanf("%d %d",&x,&n); if(n>0) { for(i=1;i<=n;i++) { f=f*i; } p=(float)pow(x,n)/f; printf("The value of p is %.3f",p); } if(n==0) { p=(float)pow(x,n)/1; printf("The value of p is %d",p); } getch(); }

但是运行不正常。我在哪里弄错了?

PS:编辑enter image description here

c loops factorial
1个回答
1
投票
在您的问题中,我已经识别出3个问题。

  1. 主要问题是scanf("%d %d",&x,&n);应更改为scanf("%f %d",&x,&n);因为x是`float type @dragosht提到过它。
  2. [printf("The value of p is %d",p);应该正确,因为printf("The value of p is %f",p);因为p也是float类型。
  3. 最好在开始时设置p = 0;,因为您没有使用键盘将值分配给p。在那里,有时您会因此而损坏值。
© www.soinside.com 2019 - 2024. All rights reserved.