我目前正在学习c,当我使用浮点返回函数时,它总是在小数点后输出为零。例如:产量为523000000但应该是523.3333333
当我将每个变量都更改为float时,当float用于所有变量时,它会给出以下错误。
#include <stdio.h>
main ()
{
float r,ans;
printf("r=");
scanf("%f",&r);
ans =volume(r);
printf("volume of sphere is %f",ans);
return 0;
}
volume(float x)
{
float v;
v= (4/3.0)*(3.14)*x*x*x;
return(v);
}
`#include <stdio.h>
// when int is used for r
main ()
{ int r;
float ans;
printf("r=");
scanf("%d",&r);
ans =volume(r);
printf("volume of sphere is %f",ans);
return 0;
}
volume(int x)
{
float v;
v= (4/3.0)*(3.14)*x*x*x;
return[output when int is used for r variable](https://i.stack.imgur.com/f6KwJ.png)(v);
}
您所需要做的就是声明返回类型,如下所示:float volume(float x)
。
如注释中所述,函数需要指定的返回类型(它们应该返回什么样的值,或者如果不返回任何值,则返回void
)。例如,float foo() { ... }
是好的,但foo() { ... }
不是。为了兼容性,后者默认返回int
,但编译器可能会抱怨。
函数volume
是在没有返回类型的情况下声明的,因此编译器假定它返回一个int
,并进行抱怨(所附的图像显示了抱怨)。
程序打印523.000000
的原因是,当从函数volume
返回v
时,强制将其转换为int
,从而丢失小数点后的精度。当存储在ans
中时,会进行另一次转换,将其转换回float
,但精度已经丢失。
为了更加清晰,这里把所有的东西都放在一起了。
#include <stdio.h>
float volume(float x) {
float v;
v = (4/3.0)*(3.14)*x*x*x;
return v;
}
int main() {
float r, ans;
printf("r=");
scanf("%f", &r);
ans = volume(r);
printf("volume of sphere is %fn", ans);
return 0;
}
祝你学习C好运!