1

I was a writing a program to invert a 5 digit number in vs code and it goes like this:

// Program to reverse the number
#include <stdio.h>
#include <math.h>
int main()
{
    int num, rev_num, a, temp,i;
    printf("\nEnter the number to be reveresed: ");
    scanf("%d", &num);
    a = 0;
    for (i = 4; i > (-1); i--)
    {
        temp = num % 10;
        num = (num - temp) / 10;
        a = a + temp * pow(10, i);
    }
    printf("\nThe reverse number is: %d",a);

    return 0;
}

One of the input is here: INPUT PIC It yielded the output by subtracting 1 from the last digit. Similar is the case with other inputs too.

It yielded the correct output in all the c compilers except vs code. Is there some bug in the vs code or my program is wrong.

  • 1
    VS Code isn't a compiler, it's an IDE. – Barmar Sep 02 '22 at 04:41
  • Unrelated to your "compiler" issue, but... If the number is "12300", you will need `%05d` as your format specifier for `printf( )` to get "00321"... Jus' sayin'.. – Fe2O3 Sep 02 '22 at 05:31
  • As additionally needed debugging info, please provide the sample input which triggers the misbehaviour and report the details of the symptoms of the misbehaviour. – Yunnosch Sep 02 '22 at 05:37
  • 1
    @Barmar Seeing all the VS-code setup related questions here, I'd hesitate to use "IDE". It seems more like a "tbsIDEar", to be self-integrated development environment, assembly required... – Yunnosch Sep 02 '22 at 05:39
  • @Yunnosch I have added an input of the same – Hari Om Mishra Sep 02 '22 at 05:51
  • 1
    Please have a look at https://meta.stackoverflow.com/a/285557/7733418 which largely also applies to data, to anything textual. – Yunnosch Sep 02 '22 at 06:50
  • Welcome to SO. Please don't let it become a habit to post pictures of text. Your output is plain text. Don't treat it as graphical artwork. Just copy&paste as formatted text into your question. – Gerhardh Sep 02 '22 at 07:44
  • Short answer: Don't use `pow()` for things like this. Possible duplicate: [Why pow(10,5) = 9,999](https://stackoverflow.com/questions/9704195)? – Steve Summit Sep 02 '22 at 16:43

1 Answers1

2

You are using a float function for integer purposes.
Getting an off-by-one problem is normal when doing so.
Compare Is floating point math broken?

The dirty details of floats where integers should be used can also easily explain differences between seemingly correct behaviour on one compiler and incorrect results on others.

So, assuming your question is "Is there some bug in the vs code[?] or my program is wrong[?]". I'd say there proabbly is a bug in VSCode (because I simply assume that for any larger program out there...), but not one explaining your observation. The problem is in your code.

In this case it would be easy to keep an increment (*10 instead of +1) number, which goes through values 1, 10, 100, 1000.

The point is to avoid floating points when the input, the output and the logic of the goal is integer.

Most elegantly (by which I mean with least changes to your code) this can be done by calculating a incrementally ("increment" by *10, not by +1). I.e. by multiplying by 10 each loop iteration.

I.e. instead of using pow(), to update a, do:

a = a*10 + temp;

This way, whatever is inside a at the start of the iteration (0 the first time) gets "moved to the left" and the 1-valued digit of the input number, which is found in temp is added.

Because of the way the integer / works you can also simplify the previous line to num = num / 10;, but that line as it is in your code also works fine.

This does not explicitly contain a variable which "increments" 1, 10, 100, it is more that a is going through temporary result values, which are in effect multiplied by 1, 10, 100, ... but the core of the idea is there and I think the minimal change to your code is an advantage of this solution.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
  • You should include the fix to the problem (use `round()`) – Barmar Sep 02 '22 at 12:14
  • @Barmar I do not think that an integer goal should be pursued by rounding anything. It would be at odds with the core of my answer. – Yunnosch Sep 02 '22 at 12:19
  • Then show your recommended fix. It's not clear what you mean in the last line. – Barmar Sep 02 '22 at 12:21
  • I will (though the "question" is so free of a question that answering it is hard). It will however be a few hours later. Have an appointment now. What I mean in the last line is to do something like keeping a value 1, 10, 100, 1000 in a variable, which is incrementally updated (instead of fully calculated) each iteration. But actually I now think there is an even more efficient way which I probably present instead. – Yunnosch Sep 02 '22 at 12:23
  • @Barmar I did provide the code. I hope you agree that the initially provided outline of the solution is still applicable, even though not exactly visible. I value your input on whether this "hidden" increment value is confusing or not. If it is confusing I would drop the attempt to stick to my initial answer and just let it be a solution with minimal change to OPs code and reprhase the first part of my answer. – Yunnosch Sep 02 '22 at 16:47
  • Nitpick: you've got the right answer for the wrong reason. The reason `pow()` doesn't work here is *not* because of the "[Is floating-point math broken?](https://stackoverflow.com/questions/588004)" problem. It's because `pow(a, b)` is often simplemindedly implemented as `exp(log(a) * b)`, and is therefore not guaranteed to give a perfect integral answer even when it otherwise could. – Steve Summit Sep 02 '22 at 16:47
  • @SteveSummit Without contradicting you on the technical detail, I consider that to match "caused by dirty details of float where integers should be used". – Yunnosch Sep 02 '22 at 16:49
  • You know, I've only belatedly looked at the answers at the "better" [question I linked to](https://stackoverflow.com/questions/9704195), and they tend to wave their hands and talk vaguely about "floating point inaccuracies", too, so I guess I can't complain. My point is that a mantra of "floating point is always inaccurate, just don't expect it to be exact" (which I used to subscribe to, precisely, myself) is a notch or two too pessimistic. One you learn to appreciate it, floating point isn't broken at all, and it can be quite precise, too. (Nor are the details all that dirty. :-) ) – Steve Summit Sep 02 '22 at 16:59
  • But, of course, you're absolutely right that for this question, there's no need to use floating point at all. The fact that C doesn't have an exponentiation operator, but does have a `pow()` function, that isn't perfect, are all holdovers from C's infancy, when it was expected to be used by programmers who knew what they were doing, and didn't need much hand-holding. – Steve Summit Sep 02 '22 at 17:01
  • I think I am with you all the way. @SteveSummit To the point of considering to use my hammer and make this a duplicate. But my feeling says that the explanation is good there, while the core of my answer here (avoid float for integer goals) merits staying an answer. I might rephrase a little, but the first rereading did not yield an improvement... – Yunnosch Sep 02 '22 at 17:06
  • So basically the problem was how a command is being processed on a compiler – Hari Om Mishra Sep 03 '22 at 03:23
  • No. The problem was in this case, that for solving an integer problem a float function was used. The float return value, which makes sense within reasonable precision in a float context, was interpreted as an integer. If the wrong method of undoing the integer->float is used, because the minimal float difference gets blown up into a full integer difference, you get an unexpected result. The error is not that the unstable result is with one compiler as you expect and with a different compiler not. The error is to take the risk by going to float in the first place. Stay integer, do not convert. – Yunnosch Sep 03 '22 at 08:54
  • I.e. not **how** the `pow()` was executed is the problem. The problem is **that** `pow()` was used. – Yunnosch Sep 03 '22 at 08:56