问题
I know you're usually not meant to put out all of your code but this is short and would help with the problem. Can anyone please explain why the output is 0 and how I can change the code to output what should be the volume of a cone.
#include <stdio.h>
float ConeVolume(int height, int radius);
float ConeVolume(int height, int radius)
{
float pi;
pi = 3.14159;
float third;
third = (1/3);
float vol;
vol = third * pi * radius * radius * height;
return vol;
}
int main()
{
float x = ConeVolume(12,10);
printf("%.4f \n", x);
}
edit: thank you to all who answered so quickly. Great community here.
回答1:
1/3
is an integer division and always results in 0
.
To have this evaluate to a floating point variable you might do
1./3
or
1/3.
or
1./3.
or even more explicit
(float)1/(float)3
for example.
回答2:
Try this;
#include <stdio.h>
float ConeVolume(int height, int radius)
{
float pi, vol;
pi = 3.14159;
vol = (pi * radius * radius * height) / 3;
return vol;
}
void main()
{
float x = ConeVolume(12,10);
printf("%.4f \n", x);
system("pause");
}
来源:https://stackoverflow.com/questions/32932941/in-c-my-output-of-a-function-is-always-0-000000-is-it-because-the-two-inputs-a