Consider:
// Decimal into octalenter image description here
#include <stdio.h>
#include <math.h>
int main()
{
int num, r = 0, octal, i = 1;
printf("Enter the number you want to convert into ocal form: ");
scanf("%d", &num);
while (num)
{ // num = 123 // num = 15 // num = 1
r = num % 8; // r = 3 // r = 7 // r = 1
octal = octal + r * pow(10, i); // octal = 3 // octal = 73 // octal = 173
i++; // i == 1 // i = 2 // i = 3
num = num / 8; // num = 15 // num = 1 // num = 0
}
printf("Octal equivalent is %d", octal);
return 0;
}
// Output
Enter the number you want to convert into ocal form: 16
Octal equivalent is 2396360
The output is not what it has to be. I think I applied the logic correctly, but... What is my mistake?
You do not initialize octal
, and you initialize i
to 1. Both of them should be initialized to 0.
It is also a bad idea to use pow
to calculate integer powers of 10. (Because it is wasteful and because some implementations of pow
are bad and do not return accurate results.) Just start a running product at 1 and multiply it by 10 in each iteration.