Search code examples
cscanfinteger-division

Why is my C Code miscalculating


I'm trying to write a formula to calculate the volume of a sphere with user inputting the radius. The formula is V = (4/3)PI r*r*r. I can't figure out why my code is just saying the volume is 1 no matter what the input is. Here is what I'm using:

#include <stdio.h>

int main(void) {

    float pi, r, v;

    pi = 3.1416;

    printf("What is the radius?\n");
    scanf("%d", &r);

    v = ((4/3) * pi) * r * r * r;

    printf("Volume of the sphere is: %d\n", v);

    if (v>10)
        printf("Volume is greater than 10");

    return 0;
}

Solution

  • There are multiple problems as I see it.

    First of all,

      scanf("%d", &r);
    

    should be

     scanf("%f", &r);
    

    as r is a float. Passing an incompatible type as argument causes undefined behavior. Please double-check the format specifier and the supplied argument type.

    The same is applicable for

         printf("Volume of the sphere is: %d\n", v);
    

    also, as %f expects a float (or double, to be exact, a float, after default argument promotion gets promoted to a double, anyway), not %d.

    With additional options enabled compiler are likely to warn you about the mismatch (at least, gcc can do that). Enable all warnings and it should point out the issue for you.

    Then, later

       v = ((4/3) * pi) * r * r * r;
    

    the 4/3 yields an integer division (giving 1) so it will not do what you think it does. You need to enforce floating point division, if you want it, with something like:

    v = (pi * 4 / 3) * r * r * r;
    

    (where the float pi multiplied by 4 gives a float, that stays a float when dividing by 3).