Home > database >  Specifying float or double yet getting int value
Specifying float or double yet getting int value

Time:12-20

#include <stdio.h>

int diameter_fn(int r)
{
    return (2 * r);
}
void circumference_fn(int r)
{
    float pie = 22 / 7;
    float circum = (2 * pie * r);
    printf(", Circumference = %f", circum);
}
void area_fn(int r)
{
    float pie = 22 / 7;
    float area = (22 * r * r / 7);
    printf(" & the Area = %f", area);
}

int main()
{
    printf("\nName = Parth_Agrawal & UID = 22BCS10924\n");
    int radius;
    printf("Enter the Radius of Circle:\t\t");
    scanf("%d", &radius);
    printf("\nDiameter = %d", diameter_fn(radius));
    circumference_fn(radius);
    area_fn(radius);
    return 0;
}

I want to calculate Circumference, diameter and area of circle using functions yet I get non-perfect Circumference and area values.

I already tried replacing the float with double, %f with %lf etc but I am always getting the Circumference and area in xxx.0000 format,I.e, similar to Int converted to float format. Like the area for 4 unit radius is 50.27 but it is giving me 50.000000 which is too much annoying. This is the Result I am getting Result I am getting whereas this is the Result which I should get Result which I should get

CodePudding user response:

... but it is giving me 50.000000 ...

OP is using integer math in many places where floating point math is needed.

void circumference_fn(int r) {
    float pie = 22 / 7;            // Integer math!!
    float circum = (2 * pie * r); 
    printf(", Circumference = %f", circum);
}

void area_fn(int r) {
    float pie = 22 / 7;           // Integer math!! pie not used
    float area = (22 * r * r / 7);// Integer math!!
    printf(" & the Area = %f", area);
}

Instead use FP math.
Scant reason to use float. Use double as the default FP type.
Rather than approximate π with 22/7, use a more precise value.

#define PIE 3.1415926535897932384626433832795
void circumference_fn(int r) {
    double circum = (2 * PIE * r);
    printf(", Circumference = %f", circum);
}

void area_fn(int r) {
    double area = PIE * r * r;
    printf(" & the Area = %f", area);
}

Other

  • All three functions should take a double argument and return a double.

  • Use "%g" for printing. It is more informative with wee values and less verbose with large ones.

CodePudding user response:

@Shawn is right: you are using integer math to calculate Pi. You should #include <math.h> and use M_PI instead of trying to calculate it yourself.

  • Related