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;
}
4
  • 2
    I suspect it is due to floating-point issues when you invoke pow() - which returns a double, not an integral type. Jun 13, 2019 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, 2019 at 18:43
  • Cannot reproduce Jun 13, 2019 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, 2019 at 19:20

1 Answer 1

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++.

2
  • 2
    I don't think pow(10,i) would return anyting close to 199.999999 for integer i...
    – CiaPan
    Jun 13, 2019 at 19:02
  • @CiaPan True, I meant the value output from pow, so it would probably be 2*pow(10,2) for the 200, returning 199.9999 instead. Jun 13, 2019 at 19:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.