could someone please check this code and tell me where i went wrong... it always gives the result 1.00000 but as you can see in the for loop it shouldn't be like that.

#include <cstdio>
int main(void)
{
    int n;
    float s = 0;
    scanf("%d", &n);
    for(int i = 1; i <= n; i++)
            {
            if(i % 2 == 0) s -= 1/(i*i);
            else s += 1/(i*i);    
            }            
    printf("%1.5f", s);
    scanf("\n");
    return 0;
}

You need to be working with floats on the right-hand side to get floating-point division. Right now you are doing integer divisions. s -= 1.0/(i*i); This one gets everyone at least once a year. Hope this helps.

Typecasting worked for me

if(i % 2 == 0) s -= 1/(float)(i*i);
            else s += 1/(float)(i*i);

hmm, thanks alot people... i never really did typecasting.. works!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.