1

i want to replace 5 with 6 and print the number

i want to replace 5 with 6 and print the number but i cant understand whats wrong in my code. for instance when i give 200 the output should be same i.e 200 but it gives 199 and when i give 205 as input instead of giving 206 as output it gives 205 itself.

#include<stdio.h>
#include<math.h>
int main()
{
    int n,i=0,r,sum=0;
    while(1){
        printf("\nenter no\n");
        scanf("%d",&n);
        while(n>0)
        {
            r=n%10;
            printf("r is= %d\n",r);
            if(r==5)
            {
                r=6;
            }
            sum=sum+(r*pow(10,i));
            n=n/10;
            i++;
        }
        printf("new no is:\t %d",sum);
        sum=0;i=0;
    }
    return 0;
}
Govind Parmar
  • 20,656
  • 7
  • 53
  • 85
  • 2
    I suspect it is due to floating-point issues when you invoke `pow()` - which returns a `double`, not an integral type. – David Collins Jun 13 '19 at 18:43
  • 4
    One obvious problem is that you're calling `pow`. That's a floating-point function that does not produce exact results. It's also completely unnecessary for your application. Get rid of `i`, and replace it with a multiplier that starts at `1`. Multiply it by `10` each time through the loop. – Tom Karzes Jun 13 '19 at 18:43
  • [Cannot reproduce](http://coliru.stacked-crooked.com/a/b9d82d13b48ffcea) – Mooing Duck Jun 13 '19 at 18:45
  • 1
    ***Use a debugger.*** Step through your code line-by-line, and inspect your variables! (Your code is short, so it would be easy) – abelenky Jun 13 '19 at 19:20

1 Answers1

4

Like others have noted, it's a floating-point arithmetic problem, the value pow outputs is little bit less than the desired value (ie. getting 199.999999 instead of 200, so it gets rounded to 199). There is a similar post about this behaviour.

Anyway, if you just want it to work you could replace this line:

sum=sum+(r*pow(10,i));

with:

 sum=sum+(r*(int)(pow(10,i)+0.5));

and it will get rounded just right. Once again, this is just a fast solution that'll help you make the program work, as I assume you are a begginer in C.

But I STRONGLY advise you to read about the floating-point arithmetic behaviour in programming languages, and why using pow on integers is a bad practice in C/C++.

123rightback123
  • 114
  • 2
  • 2
  • 13