954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

stuck

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;
}
wellibedamned
Light Poster
33 posts since May 2008
Reputation Points: 10
Solved Threads: 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.

Duoas
Postaholic
2,043 posts since Oct 2007
Reputation Points: 1,140
Solved Threads: 229
 

Typecasting worked for me

if(i % 2 == 0) s -= 1/(float)(i*i);
            else s += 1/(float)(i*i);
hammerhead
Posting Whiz in Training
257 posts since May 2006
Reputation Points: 46
Solved Threads: 24
 

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

wellibedamned
Light Poster
33 posts since May 2008
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You