在 C 中,我的函数输出总是 0.000000。是不是因为两个输入都是int?

In C, my output of a function is always 0.000000. Is it because the two inputs are int?

我知道您通常不打算发布所有代码,但这很短,可以帮助解决问题。任何人都可以解释为什么输出为 0 以及我如何更改代码以输出圆锥体的体积。

#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);
}

编辑:感谢所有这么快回答的人。这里有很棒的社区。

1/3

是整数除法,结果总是 0

要将此计算为浮点变量,您可以这样做

1./3

1/3.

1./3.

甚至更明确

(float)1/(float)3

例如

试试这个;

#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");
}