I am currently learning c , when I use a function with return using float it always gives output as zero after decimal point. eg: output is 523.000000 but it should have been 523.333333
when I change every variable to float, it gives the below when float is used for all variableerror.
#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.sstatic.net/f6KwJ.png)(v);
}
All you need to do is state the return type, like so: float volume(float x)
.
As mentioned in the comments, functions need a specified return type (what kind of value they should return, or void
if they return nothing). For example, float foo() { ... }
is fine but foo() { ... }
is not. The latter will default to returning an int
for compatibility, but a compiler will probably complain.
Function volume
is declared without a return type, so the compiler assumes it returns an int
, and complains (the image you attached shows the complaint).
The reason your program prints 523.000000
is because you force v
to be converted to an int
when you return it from function volume
, losing the precision after the decimal. When stored in ans
, another conversion takes place to turn it back into a float
, but the precision has already been lost.
Here's everything put together for extra clarity.
#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 %f\n", ans);
return 0;
}
Good luck learning C!