stuck

Please support our C++ advertiser: Intel Parallel Studio Home
Reply

Join Date: May 2008
Posts: 29
Reputation: wellibedamned is an unknown quantity at this point 
Solved Threads: 0
wellibedamned wellibedamned is offline Offline
Light Poster

stuck

 
0
  #1
May 25th, 2008
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.
  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. }
Reply With Quote Quick reply to this message  
Join Date: Oct 2007
Posts: 1,953
Reputation: Duoas has much to be proud of Duoas has much to be proud of Duoas has much to be proud of Duoas has much to be proud of Duoas has much to be proud of Duoas has much to be proud of Duoas has much to be proud of Duoas has much to be proud of 
Solved Threads: 214
Featured Poster
Duoas's Avatar
Duoas Duoas is offline Offline
Posting Virtuoso

Re: stuck

 
0
  #2
May 25th, 2008
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.
Reply With Quote Quick reply to this message  
Join Date: May 2006
Posts: 248
Reputation: hammerhead is an unknown quantity at this point 
Solved Threads: 24
hammerhead's Avatar
hammerhead hammerhead is offline Offline
Posting Whiz in Training

Re: stuck

 
0
  #3
May 25th, 2008
Typecasting worked for me
  1. if(i % 2 == 0) s -= 1/(float)(i*i);
  2. else s += 1/(float)(i*i);
There are 10 types of people in the world, those who understand binary and those who don't.

All generalizations are wrong. Even this one.
Reply With Quote Quick reply to this message  
Join Date: May 2008
Posts: 29
Reputation: wellibedamned is an unknown quantity at this point 
Solved Threads: 0
wellibedamned wellibedamned is offline Offline
Light Poster

Re: stuck

 
0
  #4
May 25th, 2008
hmm, thanks alot people... i never really did typecasting.. works!
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Similar Threads
Other Threads in the C++ Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC