Home > Back-end >  Why is this code not performing the calculation correctly? Volume of a sphere given a radius
Why is this code not performing the calculation correctly? Volume of a sphere given a radius

Time:10-25

Title says is all. The math is wrong for calculating the volume given a radius, but the calculation for the area is correct.

#define _CRT_SECURE_NO_WARNINGS
#define _USE_MATH_DEFINES

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

float radius[4][3];
int x = 0;
int main()
{
    while (x < 4)
    {
        printf("Please enter Radius %d: ",(x 1));
        scanf("%f", &radius[x][0]);
        radius[x][1] = ((4 / 3) * M_PI * pow(radius[x][0], 3));
        radius[x][2] = M_PI * pow(radius[x][0], 2);
        x  ;
    }
    x = 0;
    while (x < 4)
    {
        printf("\n\rThe volume for a sphere with the radius %.2f is %.2f", radius[x][0], radius[x][1]);
        printf("\n\rThe area for a circle with the radius %.2f is %.2f", radius[x][0], radius[x][2]);
        x  ;
    }
    return 0;
}

CodePudding user response:

4 / 3 has integers for both operands, so integer division is performed. This truncates the result toward 0, giving a result of 1.

Use floating point constants to perform floating point division.

radius[x][1] = ((4.0 / 3.0) * M_PI * pow(radius[x][0], 3));

CodePudding user response:

In this line: radius[x][1] = ((4 / 3) * M_PI * pow(radius[x][0], 3));

This operator (4 / 3) is an integer division, because both left and right operands are integers {4 and 3) so it will truncate to 0.

4 / 3 = 1.33333333333333333... but the result is truncated, so it will return 1.

Use floating point:

radius[x][1] = ((4.0 / 3.0) * M_PI * pow(radius[x][0], 3));

Or typecast it into float type.

radius[x][1] = (((float)4 / 3) * M_PI * pow(radius[x][0], 3));

CodePudding user response:

In addition to going from integer division where (4 / 3) is 1 to floating point division, consider using consistent math types:

double radius[4][3];
radius[x][1] = ((4.0 / 3.0) * M_PI * pow(radius[x][0], 3));
radius[x][2] = M_PI * pow(radius[x][0], 2);

or

#define M_PIf 3.1415926535897932f
float radius[4][3];
radius[x][1] = ((4.0f / 3.0f) * M_PIf * powf(radius[x][0], 3));
radius[x][2] = M_PIf * powf(radius[x][0], 2);

I'd stay with double and take advantage of prior multiplications rather than call expensive pow().

double radius[4][3];
radius[x][2] = M_PI * radius[x][0] * radius[x][0];
radius[x][1] = (4.0 / 3.0) * radius[x][2] * radius[x][0];
  • Related