3

I am trying to print the incremented values up to the given number by (0.1). I am getting two inputs x and y and then I am trying to print the values from x to y incremented by 0.1, but i am facing the problem. Below is my code. Thanks in advance.

#include<stdio.h>
int main()
{
float x,y,i;
scanf("%f %f\n",&x,&y);
for(i=x;i<=y;)
 {
  printf("%.1f ",i);
  i=i+0.1;
 }

Input: 9.4 10.2

Output:

9.4 9.5 9.6 9.7 9.8 9.9 10.0 10.1

Expected Output:

9.4 9.5 9.6 9.7 9.8 9.9 10.0 10.1 10.2

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • 6
    `10.10000000000000000074623452 + 0.1 > 10.2` – pmg Feb 21 '19 at 15:30
  • what should be the correct solution for this? – Akash kumar Feb 21 '19 at 15:31
  • 2
    Use integers; scale by `10`; divide by `10` when printing: `for (int i = x*10; i <= y*10; i += 1) { printf("%.1f ", i / 10.0); }` – pmg Feb 21 '19 at 15:33
  • 2
    Rule of thumb with floating point numbers: don't ever compare for equality or less or equal, or higher or equal. Only use `<` and `>`, never `<=`, `>=` or `==`. – Jabberwocky Feb 21 '19 at 15:36
  • some other duplicates: [Why "for( i = 0.1 ; i != 1.0 ; i += 0.1)" doesn't break at i = 1.0?](https://stackoverflow.com/q/13542220/995714), [Strange loop on Java for 0.1 to 2](https://stackoverflow.com/q/5400565/995714), [Condition to check double is an integer not working](https://stackoverflow.com/q/54750758/995714)... – phuclv Feb 21 '19 at 15:40
  • 1
    @Akashkumar To provide a correct solution you have to specify, what the actual problem is. The root cause of the issue is rounding errors, so an arbitrary precision library like gmp would work. It might be overkill, however. – Ctx Feb 21 '19 at 15:48
  • @pmg: This question is not a duplicate of [that question](https://stackoverflow.com/questions/588004/is-floating-point-math-broken), and that question does not explain how to iterate through floating-point values. Please do not promiscuously close floating-point question as a duplicate of that one. **It does not answer most floating-point questions.** – Eric Postpischil Feb 21 '19 at 15:55
  • Noted @EricPostpischil, I'll be more careful – pmg Feb 21 '19 at 16:04
  • Upvoting for a question that includes a [mcve], input, desired output and actual output. Thanks! – Tim Randall Feb 21 '19 at 16:54

0 Answers0