0

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.

C. Doe
  • 3
  • 2
  • 1
    Compile with all warnings & debug info (`gcc -Wall -Wextra -g`). Then use the debugger (`gdb`) by single stepping your program. You would have found your bug quickly (faster than asking here). – Basile Starynkevitch Oct 04 '15 at 11:29
  • there are uncountable duplicates of this on SO – phuclv Oct 04 '15 at 11:48

2 Answers2

7
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.

alk
  • 69,737
  • 10
  • 105
  • 255
0

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