Search code examples
carea

How to find empty space in a rectangle which has 2 circles in it?


I'm solving a problem in Toph . In this problem I've to find out the empty space of a rectangle which has 2 equal circles in it.

here is the problem

#include <stdio.h>
float pi=3.1416;
int main()
{
    int i,t;
    float r,rest;
    scanf("%d",&t);
    for(i=1;i<=t;i++)
    {
        scanf("%f",&r);
        rest=(4*r*2*r)-(2*pi*r*r);
        printf("Case %d: %.2f\n",i,rest);
    }
    return 0;

Here is my solve. It returns a correct value for first test case but it fails to solve the second one. What's the problem???


Solution

  • float pi=3.1416; is the cause of the problem. Under the math header file (#include <math.h>) there is a constant M_PI use it instead.

    Edit: Sorry, didn't read thoroughly, apparently the problem is in the floating point precision. If you change all float values into double it should work.

    #include <stdio.h>
    double pi=3.1416;
    int main()
    {
        int i,t;
        double r,rest;
        scanf("%d",&t);
        for(i=1;i<=t;i++)
        {
            scanf("%lf",&r);
            rest=(4*r*2*r)-(2*pi*r*r);
            printf("Case %d: %.2lf\n",i,rest);
        }
        return 0;
    }