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

int main(){
  int num,onum,numl=0,tem,nnum=0;    

  printf("Enter num: ");
  scanf("%d", &num);

  onum =num;

  while (num!=0){
    num = num/10;
    ++numl;
  }
  num = onum;

  while (num!=0){
    tem = num%10;

    nnum += pow(tem,numl);
    printf("%d",nnum);
    num /= 10    ;
  }

  if (nnum == onum){
    printf("is");
  }
  else{
    printf("not");
  }
}

works fine with other Narcissistic numbers .

but when input 153 , 5**3 is mistakenly counted to 124, why? enter image description here


This question is duplicate of many questions. And the answer below is the most easy-to-understand anwer.

In one sentence, the inaccurate calculation is caused by {inaccurate {data type usage} or {compiler} or {FPU} }.

I avoided the error by updating my compiler to gcc 7.2 . But solving the problem needs a pow function for integer.

userA789
  • 425
  • 2
  • 6
  • 17
  • try to add more details, using spam to fill in words is a bad practice – Louis-Roch Tessier Aug 30 '17 at 12:21
  • [Why pow(10,5) = 9,999](https://stackoverflow.com/q/9704195/995714), [Will (int)pow(n,m) be wrong for some positive integers n,m?](https://stackoverflow.com/q/32353301/995714), [return value of pow() gets rounded down if assigned to an integer](https://stackoverflow.com/q/7937286/995714) – phuclv Aug 31 '17 at 05:33
  • the general solution is to round the results to the nearest integer – phuclv Mar 03 '18 at 10:08
  • I edit it to correct my wrong word-use. – userA789 Mar 03 '18 at 10:15

1 Answers1

3

pow (in pow(tem,numl)) is a floating point function. It means that it returns a double, bound to floating point inaccuracy and rounding (if pow returns 124.999999 it has no impact for floating point computation, but it does when assigned to an integer because of truncation)

So relying on the return value of pow may work, or may not (depends on the values, the FPU, the compiler math libraries). And the fact that "sometimes it issue a slightly off value" is a giveaway for that floating point inaccuracy issue.

Since you're working exclusively with integers, I would use integer exponentiation instead, either with a simple loop or with more complex algorithms (The most efficient way to implement an integer based power function pow(int, int))

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • 1
    I am interested, why then this code work in my case - Ubuntu 16.04, `gcc version 5.4.0`? – MiniMax Aug 30 '17 at 21:13
  • this code works for me too (gcc 6.1). But it depends on the FPU and on the math library. It's better _not_ to depend on it and use strictly integer arithmetic. thanks for your comment. I have updated the answer. – Jean-François Fabre Aug 30 '17 at 21:14