1

I'm trying to learn C, but currently stuck. I'm trying to get the same output as below, but I'm not sure how to round the last few decimals points in my code to get the same output below.

1. ENTER AN INTEGER
2. 5
3. DIAMETER: 10.000000
4. CIRCUMFERENCE: 31.415900
5. AREA: 78.539750

int main()
{
     float num1, diameter, circumference, area;

    printf("ENTER AN INTEGER\n");
    scanf("%f", &num1);

    diameter = 2 * num1;
    circumference = 2 * 3.14159 * num1;
    area = 3.14159 * (num1 * num1);

    printf("DIAMETER: %f\n", diameter);
    printf("CIRCUMFERENCE: %.6f\n", circumference);
    printf("AREA: %.6f\n", area);


    return 0;
}

The output of my result.

1. ENTER AN INTEGER                                                                        
2. 5                                                                                       
3. DIAMETER: 10.000000                                                                     
4. CIRCUMFERENCE: 31.415899                                                                 
5. AREA: 78.539749   
Rzxd
  • 11
  • 2

2 Answers2

1

In typical C implementations, changing float to double and scanf("%f", &num1); to scanf("%lf", &num1); will provide sufficient precision to get the desired output in this case.

In general, you should expect small rounding errors in floating-point operations (which may grow to large errors with complicated sequences of numerous operations).

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
0

As @Eric Postpischil says, your decimals error are due to operations with float numbers (single precision -32 bits-) have small precision errors. A double number (double precision -64 bits-) will solve your precision problem.

Here you have some information about the three decimal types: Decimal types

A working example code for your chase is:

int main()
{
    double num1, diameter, circumference, area;

    printf("ENTER AN INTEGER\n");
    scanf("%lf", &num1);

    diameter = 2 * num1;
    circumference = 2 * 3.14159 * num1;
    area = 3.14159 * (num1 * num1);

    printf("DIAMETER: %lf\n", diameter);
    printf("CIRCUMFERENCE: %.6lf\n", circumference);
    printf("AREA: %.6lf\n", area);

    return 0;
}
JuMoGar
  • 1,740
  • 2
  • 19
  • 46