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

耗尽温柔 提交于 2021-02-08 10:42:23

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!