Decimal To Octal Converter, last digit issue
- by Srishan Supertramp
I tried making a C program to convert a user entered decimal number to octal. I wrote the C code with my own logic without any research of how other users try to do it. It works fine for the number 601 and some other numbers but for most numbers it returns the octal equivalent with the last digit being 1 less than it should be. For 75 it returns 112 instead of 113. I realize using printf with %o gets the job done but it's kind of defeating the purpose of learning to program. Here's my code:
#include <stdio.h>
#include <math.h>
/* converting decimal to octal */
int main()
{
int n,x,y,p,s;
printf("Enter a decimal number ");
scanf("%d",&x);
s=0;p=0;
while (x!=0)
{
y=x%8;
s=s+y*pow(10,p);
x=(x-y)/8;
p=p+1;
}
printf("the octal equivalent is: %d\n",s);
getch();
return 0;
}