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.

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). Commented Oct 4, 2015 at 11:29
  • there are uncountable duplicates of this on SO Commented Oct 4, 2015 at 11:48

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I was about to add (not quite serious) that it's not the ./ operator in action there :) But then you showed the other variations and I think it became clear that you are dividing floats :)
Ah yes, missed the ./-operator ... dxxm, failed again ;-) @JohannesSchaub-litb
It is not a ./ operator, it is a / operator applied to 1. and 3
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"); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.