float vs int creating confusion

I was solving for SPOJ : MAXLN here is some code

CASE 1

#include <cstdio>

int main()
{
    int T,r;                  // r is integer here
    float ans;
    scanf("%d",&T);
    for(int i=1;i<=T;i++){
        scanf("%d",&r);
        ans = 4*r*r + 0.25;
        printf("Case %d: %.2f\n",i,ans);
    }
    return 0; 
}

Input :- 2 1 1000000
Output :- 4.25 1385447424.00

CASE 2

#include <cstdio>

int main()
{
    int T;
    float ans,r;
    scanf("%d",&T);
    for(int i=1;i<=T;i++){
        scanf("%f",&r);
        ans = 4*r*r + 0.25;
        printf("Case %d: %.2f\n",i,ans);
    }
    return 0; 
}

Input :- 2 1 1000000
Output :- 4.25 3999999983616.00

CASE 2 got AC

Question :-

1 : why there is different answer for input 1000000.
2 : for input = 1000000 ans = (4 * 1000000 * 1000000) + 0.25 = 4000000000000.25 , then why CASE 2 got AC

There are upper limits on data types, don’t forget that.

rmax=106

So, r2max = 1012

So, 4 x r2max = 4 x 1012

So, you need long long

#include <cstdio>

int main()
{
    int T;
    scanf("%d", &T);

    for (int i = 1; i <= T; i++) {
        long long r;
        scanf("%lld", &r);

        float ans = 4 * r * r;
        ans += 0.25;

        printf("Case %d: %.2f\n", i, ans);
    }

    return 0; 
}
1 Like

Also getting AC with int r is not a big deal too.

#include <cstdio>

int main()
{
	int T;
	scanf("%d", &T);
	
	for (int i = 1; i <= T; i++) {
    	int r;
    	scanf("%d", &r);
    
    	double ans = 4.0 * r * r + 0.25;
    
    	printf ("Case %d: %.2f\n", i, ans);
	}

	return 0; 
}

but value is stored in ans, why r should be long long

ans = 4 * r * r, first 4rr is calculated as Integer because it’s Integer then assignment is done and implicit typecasting makes 4rr float

what about question 2

Well it should not get AC. May be test cases are not strong.