-1

Im not getting correct answer with the following code below. Can anyone debug this code? When I input radius = 5, the answer I get is 500.000000 whereas the original answer should be 523.80952. Can anyone please explain what's wrong here?

Sphere volume formula =4/3(π x r^3)

#include <stdio.h>

int main()


    {
    float radius = 0;
    float volume;
    float pie = 0;

    printf("Enter radius");
    scanf("%f", &radius);

    pie = 22 / 7;

    volume = (4*pie*radius*radius*radius)/3;
    printf("the volume is %f", volume);

    return 0;
    }
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Hamza Azam
  • 17
  • 1
  • 3
  • 10
  • "the original answer should be 523.80952". No, it should be more like `523.598776` (to 6 decimal places). 22/7 is a poor approximation to π. I'd suggest using a more accurate value. – Mark Dickinson Oct 03 '16 at 07:46

2 Answers2

2

The problem is in the line

 pie = 22 / 7;

here, both the operands of the division being integer constants, this is an integer division and the the result get assigned to float, which is not what you want. You need to force a floating point division by saying

pie = ((float)22) / 7;
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • If both the operands are integer, will I always get an integer value? – Hamza Azam Oct 02 '16 at 16:02
  • Curious, why call `22` an _integer literal_ vs maybe _integer constant_? – chux - Reinstate Monica Oct 02 '16 at 16:08
  • 1
    @chux Well, i don't think [integer literal](https://en.wikipedia.org/wiki/Integer_literal) is incorrect use, but as per the standard, it's integer constant. Edited anyway. – Sourav Ghosh Oct 02 '16 at 17:01
  • Of course, `22.0f / 7.0f` or even just `22.0f / 7` should work as well. I personally find that a tad more elegant than casting to float. – Rudy Velthuis Oct 02 '16 at 21:25
  • 1
    @SouravGhosh: I agree. The term "literal" is quite common, not only in C. If, like me, you work in different languages, especially if in one of them a constant is something different (an *identifier* like `circumference` representing a literal like `17`) you tend to use the term "literal" for, well, literal values. – Rudy Velthuis Oct 02 '16 at 21:31
1

You can also write pie = 3.14 ; instead of pie = 22 / 7 ;

And keep in mind that: (a) Arithmetic operation between two integers always returns an integer. (b) Arithmetic operation between two real numbers always returns a real number. (c) Arithmetic operation between an integer and a real number returns a real number.

So, pie = 22 / 7 will return 500.000000 instead of 523.80952. therefore you can also write pie = 22.0 / 7 or pie = 22 / 7.0 or pie = 22.0 / 7.0. These three will return the original answer.

Se7eN
  • 548
  • 1
  • 7
  • 22