-1

What I am trying to do here is, I am taking a precision value (less than 1) and printing count of all the numbers of type 1/n (n is natural number) which are greater than or equal to the precision value (input).

#include <stdio.h>

int main(){
    int i=1,terms=0;
    float n;
    printf("Enter precision value : ");
    scanf("%f",&n);

    while(i>0){
        if ((1.0/i) >= n){
            printf("%f\n",1.0/i);
            sum = sum + (1.0/i);
            terms++;
            i++;
        }
        else
            break;
    }
    printf("number of terms : %d\n",terms);
    return 0;
}

But if I give input 0.1 than the count (output) is showing only 9. but it should show 10 (it is not including 1/10).

I was using a for loop before and I know that breaking a loop with an if-else statement is not the best thing.

ab29007
  • 7,611
  • 2
  • 17
  • 43
  • I think you are confusing the term "precision" and "float". Floats are not precise. The fact that floats can do e.g. 0.125 (and integers cannot) is misleading. – Yunnosch Aug 14 '17 at 07:55

1 Answers1

2

That's just the way math works with limited precision. For example, say you're using six digits of decimal precision. The best you can do for one-third is 0.333333 and the best you can do for 2/3 is 0.666667, but then 2 * 1/3 will not equal 2/3. And 3 * 1/3 will not equal 1. But 1/3 + 2/3 will.

Just as 1/3 cannot be expressed exactly in decimal, 0.1 cannot be expressed exactly in binary. So testing for equivalence is not smart.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • But suppose my precision number (input) is 0.1. Then if I do `printf("%f",1.0/10)` and `printf("%f",n)` then they both print `0.100000` – ab29007 Aug 14 '17 at 05:06
  • Yes, because there's rounding going on everywhere, including in the printing. – David Schwartz Aug 14 '17 at 05:07
  • so if I compute `1.0/i` before the `if` condition than that should work, because then in the `if` condition rounded number will appear. – ab29007 Aug 14 '17 at 05:08
  • ok. it worked.I just did this : `while(i>0){ cond = (1.0/i); if (cond >= n){` – ab29007 Aug 14 '17 at 05:09
  • Likely it just happened to because you changed the exact sequence of instructions your platform chose to use. Working through a variable may have caused a store operation that reduced the internal precision. – David Schwartz Aug 14 '17 at 05:13
  • For example, your platform may only support doubles natively. So, to use an analogy, `1/3` might yield `0.333333333333`. But if you store it in memory as a float and read it back, you might get `0.333333` because the internal operations have more precision than the variables do. **Don't do this kind of thing!** – David Schwartz Aug 14 '17 at 05:14