0

Need help with this program for a simple decimal to octal converter. I'm using Code::Blocks 16.01 IDE with GNU GCC Compiler.

An input of 77 should produce 115 but I get 114. "oct = oct + rem * pow(10,p);" is not producing the correct output consistently. It's a digit less at times. Could this be a linker issue to the math.h header? Not sure what else to check.

Thank you.

#include <stdio.h>
#include <math.h>

int main()
{
  int n1,n2,rem,oct,p;
  printf("Enter any number: ");
  scanf("%d",&n1);

  n2=n1;
  p=oct=0;
  while (n1>0)
    {
      rem = n1 % 8;
      n1 = n1 / 8;
      oct = oct + rem * pow(10,p);
      ++p;
    }
  printf("The octal equivalent of %d is %d\n", n2,oct);
  return 0;

}    
  • Strange, I took your code, compiled and run it with 77, the output was 115. I checked other numbers and the output was correct again. Are you sure you copied your code 1:1 here? – Pablo Jan 18 '18 at 19:16
  • 1
    You are using with int a function which is meant for floating point math. If you do something like that you should be aware of the following, which might well explain your problem of different output in different environments (including wrong on yours and right on others): https://stackoverflow.com/questions/588004/is-floating-point-math-broken – Yunnosch Jan 18 '18 at 19:26
  • The `%o` format specifier will do the conversion for you. – Eugene Sh. Jan 18 '18 at 19:50

0 Answers0