You can use %o to print a octal number
check this link http://ideone.com/OLXEL7
printf("%o\n", x);
Hope this helps
سؤال
I am working on a homework problem that asks us to write a function in C that will convert from decimal to octal. Here's what I have so far
int oct(int num) {
if (num < 8) {
return num;
}
else {
}
}
So yeah I'm pretty stuck, any help is very much appreciated Thanks
المحلول
You can use %o to print a octal number
check this link http://ideone.com/OLXEL7
printf("%o\n", x);
Hope this helps
نصائح أخرى
Decimal to octal? Super easy, two functions in the stdlib.
void dec2oct(char *dst, const char *src, size_t dstsz)
{
int n = strtoll(src, NULL, 10); // treat "src" as base-10
snprintf(dst, dstsz, "%o", n); // and write it to "dst" as base-8
}
Call it like this:
char buf[32];
dec2oct(buf, "133742", sizeof(buf));
Since your function has to return an integer, you will have to build up the octal as if it's a decimal number.
Do long division by 8 to work out the digits. There are countless examples on the web for long division in C.
Then for each digit, multiply it by 10 and add to your running count. Then it will be decimal dressed as octal... Or is it the other way around....
Refer the following Program.
I hope this can help.
void print_oct(int num)
{
if (num != 0) {
print_oct(num / 8);
printf("%d", num % 8);
}
}