How to calculate the volume of glass juice?

Viewed 143

The radius of the upper part r1 and lower part r2 is given. If the height of the glass is h and height of the juice is p what is the volume of the juice in the glass? For some input-output is wrong:

#include <stdio.h>
#include <math.h>

int main() {
    int r1, r2, h, p;
    scanf("%d %d %d %d", &r1, &r2, &h, &p);
    //for juice height p we will find out the radius r3 
    float r3 = ((r1 * p) / h);  //calculating r3 by percentage formula
    float v = ((M_PI / 3) * 3 * ((r3 * r3) + (r2 * r2) + (r3 + r2)));
    printf("Volume : %f\n", v);

    return 0;
}

EDIT: After I changed the all int to double still for some input output is wrong for an example for input 5 2 3 2 the answer should be 58.64.

2 Answers

Integer division yields an integer result - 1/2 == 0, 5/2 == 2, etc., so ((r1*p)/h) is not giving you the right value.

You should declare your inputs as double instead of int and use %lf instead of %d to read them:

double r1,r2,h,p;
scanf("%lf %lf %lf %lf",&r1,&r2,&h,&p);

You'll also want to declare r3 and v as double instead of float.

Besides the errors shown in John Bode's answer, the posted code is using the wrong formulas to calculate the volume.

#include <stdio.h>
#include <math.h>

// M_PI is not a standard macro
#if !defined(M_PI)
#define M_PI 3.14159265358979323846
#endif

int main(void)
{
    // Given the following calculations, I'd use a floating-point type
    // to store the values.
    double r1, r2, h, p;

    // The format specifiers need to be changed accordingly.
    scanf("%lf%lf%lf%lf", &r1, &r2, &h, &p);
    
    // To extimate the radius of top surface of the juice, we can't forget
    // the radius at the bottom of the glass (it's not zero!).
    double r3 = r2 + ((r1 - r2) * p) / h;

    // The volume of the conical frustum can be calculated with a formula different
    // from the posted one and we need to consider the height of the juice.
    double v = M_PI * p * (r3 * r3 + r3 * r2 + r2 * r2) / 3.0;

    printf("Volume : %f\n", v);

    return 0;
}
Related