![]() |
| | #1 |
| Registered User Join Date: Nov 2009
Posts: 3
| what am i doing wrong? Code: #include <stdio.h>
int main() {
int i;
float res;
res = 0;
for (i=1;i<=100;i++){
res = res + 1/i;
}
printf("%f",res);
getchar();
return 0;
}
result: 1???????????????????? |
| newbiecr is offline | |
| | #2 |
| Registered User Join Date: Sep 2006
Posts: 2,517
| You're doing integer division, where the remainder is thrown out, so it boils down to 1/1 = 1, and all the other divisions are zero's. So the answer is just 1. |
| Adak is offline | |
| | #3 | |
| Registered User Join Date: Nov 2009
Posts: 3
| Quote:
Code: #include <stdio.h>
#include <math.h>
int main() {
int i;
float res;
res = 0;
for (i=1;i<=100;i++){
res = res + 1.0/i;
}
printf("%f",res);
getchar();
return 0;
}
result: 5.187378 is it correct? | |
| newbiecr is offline | |
| | #4 |
| Jaxom's & Imriel's Dad Join Date: Aug 2006 Location: Alabama
Posts: 801
| Usually, it is best to define the types in the code: res = res + 1.0f/(float)i; Though this is not a requirement. |
| Kennedy is offline | |
| | #5 | |
| Mysterious C++ User Join Date: Oct 2007
Posts: 14,099
| Only one side needs to be a floating point, though.
__________________ Using: Microsoft Windows™ 7 Professional (x64), Microsoft Visual Studio™ 2008 Team System I dedicated my life to helping others. This is only a small sample of what they said: "Thanks Elysia. You're a programming master! How the hell do you know every thing?" Quoted... at least once. Quote:
| |
| Elysia is offline | |
![]() |
| Thread Tools | |
| Display Modes | |
|
Similar Threads | ||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Problem with input choice... Somethings wrong... really wrong.... | greenferoz | C++ Programming | 9 | 07-15-2004 03:30 PM |
| Debugging-Looking in the wrong places | JaWiB | A Brief History of Cprogramming.com | 1 | 11-03-2003 10:50 PM |
| Confused: What is wrong with void?? | Machewy | C++ Programming | 19 | 04-15-2003 12:40 PM |
| God | datainjector | A Brief History of Cprogramming.com | 746 | 12-22-2002 12:01 PM |
| Whats wrong? | Unregistered | C Programming | 6 | 07-14-2002 01:04 PM |