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.
CodePudding user response:
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.