943,867 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Unsolved
  • Views: 453
  • C++ RSS
May 25th, 2008
0

stuck

Expand Post »
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.
C++ Syntax (Toggle Plain Text)
  1. #include <cstdio>
  2. int main(void)
  3. {
  4. int n;
  5. float s = 0;
  6. scanf("%d", &n);
  7. for(int i = 1; i <= n; i++)
  8. {
  9. if(i % 2 == 0) s -= 1/(i*i);
  10. else s += 1/(i*i);
  11. }
  12. printf("%1.5f", s);
  13. scanf("\n");
  14. return 0;
  15. }
Similar Threads
Reputation Points: 10
Solved Threads: 0
Light Poster
wellibedamned is offline Offline
33 posts
since May 2008
May 25th, 2008
0

Re: stuck

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.
Featured Poster
Reputation Points: 1140
Solved Threads: 229
Postaholic
Duoas is offline Offline
2,039 posts
since Oct 2007
May 25th, 2008
0

Re: stuck

Typecasting worked for me
C++ Syntax (Toggle Plain Text)
  1. if(i % 2 == 0) s -= 1/(float)(i*i);
  2. else s += 1/(float)(i*i);
Reputation Points: 46
Solved Threads: 24
Posting Whiz in Training
hammerhead is offline Offline
248 posts
since May 2006
May 25th, 2008
0

Re: stuck

hmm, thanks alot people... i never really did typecasting.. works!
Reputation Points: 10
Solved Threads: 0
Light Poster
wellibedamned is offline Offline
33 posts
since May 2008

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: Interesting Problem
Next Thread in C++ Forum Timeline: get user input for file name to open?





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC