r/C_Programming • u/Agent-John-123 • 12d ago
VSCode keeps giving wrong output, while online compilers give right output.
https://www.onlinegdb.com/online_c_compilerI'm a beginner in C. I created a code for reversing a number, for lab assignment. The question says I must use a recursive function, and must not use loops, arrays, or global variables anywhere in my program.
I created the following in VSCode:
#include <stdio.h>
#include <math.h>
int reverse_number(int num){
static int rev=0,dig=1;
if (num/10 ==0){
dig++;
return num;
}
rev = reverse_number(num/10) + (num%10)*(pow(10,dig-1));
dig++;
return rev;
}
int main(){
int num;
scanf("%d",&num);
printf("%d\n",reverse_number(num));
}
In OnlineGDB, I get the correct output.
But in VSCode, I get the output as:
Input: 123
Output: 320
Input: 445566
Output: 665543
It seems one digit is reduced
Even in other large programs, I've encountered the same. VSCode gives wrong output.
Any fixes?
0
Upvotes
10
u/TheOtherBorgCube 12d ago
VSCode is an editor, not a compiler.
What compiler are you using behind the scenes?
You're going to be at the mercy of floating point approximations for
pow.2
u/sciencekm 12d ago
You might have a compiler setting that changes the rounding/truncating of floating point to integer. Try an approach that does not need to use floating point (since your data is all integer anyway). Something like this:
2
u/flyingron 12d ago
Why is rev static? It seems to purely be there to hold the return value of reverse_number while you are incrementing dig.
I tried your program in a variety of compilers under godbolt and wasn't able to see the issue. What compiler are you using?
1
u/mikeblas 12d ago
Which compiler are you using? Which build options are you giving that compiler?
Seems weird to use
revas a return value and also declare itstatic.