我用c语言编写了下面的代码来计算一个数字的指数,而不用数学库。
#include <stdio.h>
float powr(float,int);
int main(){
float a;
int b;
printf("Enter base and exponent a^b: ");
scanf("%.2f %d",&a,&b);
float p=powr(a,b);
printf("%.2f",p);
return 0;
}
float powr(float x,int y){
float r=1;
for(int i=1;i<=y;i++){
r=r*x;
}
return(r);
}但是无论我输入什么基和指数,输出总是为1.00。我在这个程序中找不到任何错误,我试着在一个单独的程序中在main()中运行powr函数算法,它可以工作。
发布于 2022-01-07 07:30:27
在scanf()中,它接受字段宽度格式,但没有精确性,参见这里。
您只需输入值,如下所示:
scanf("%f %d",&a,&b);此外,您应该始终检查scanf()的返回值。就像这样:
numOfItems = scanf("%.2f %d",&a,&b);
if(numOfItems != 2) // uh-oh
{
printf("Error while input!");
}https://stackoverflow.com/questions/70617237
复制相似问题