Decimal To Octal Converter, last digit issue
Posted
by
Srishan Supertramp
on Stack Overflow
See other posts from Stack Overflow
or by Srishan Supertramp
Published on 2012-11-02T04:11:40Z
Indexed on
2012/11/02
5:01 UTC
Read the original article
Hit count: 221
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;
}
© Stack Overflow or respective owner