Possible error in the logging of a function that returns whether an integer is an Armstrong number

Asked

Viewed 144 times

-1

Armstrong numbers are numbers that are the sum of their own digits, each raised to the number of digits.
Ex: 371 (3 digits) = 3³ + 7³ + 1³.
Knowing this, my algorithm gives error with the number 153 and only with it (the program gives me the wrong result, that is, the function returns 0), I could not find out why. I compile by gcc through vscode.

Some Armstrong numbers for testing: from 1 to 9, 153, 370, 371, 407, 1654.

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

int eh_numero_de_armstrong(int n);

int main()
{
  int x;

  printf("Digite um numero qualquer: ");
  scanf("%d", &x);

  if (eh_numero_de_armstrong(x))
    printf("%d eh um numero de Armstrong.\n", x);
  else
    printf("%d nao eh um numero de Armstrong.\n", x);

  return 0;
}

int eh_numero_de_armstrong(int n)
{
  char str[100];
  int soma_alg = 0;

  sprintf(str, "%d", n);
  for (int i = 0; i < strlen(str); i++)
    soma_alg += pow(str[i] - '0', strlen(str));

  if (n == soma_alg)
    return 1;
  else
    return 0;
}
  • What would be the mistake? The program gives you the wrong result, or it crashes? Here is functioning normally.

  • @user140828 gives me the wrong result, the function returns 0. (I will edit the question)

  • Here it worked for: 93084, 8208, 1634, 407, 371, 370 and 153.

  • Looks like it’s my compiler so I’ll try to reinstall it. Tested with gcc? @anonimo

  • 1

    You can also use some online compiler like ideone: https://ideone.com/

  • 1

    It worked perfectly in gcc. gcc version 7.4.0 (Ubuntu 7.4.0-1ubuntu1~18.04.1)

Show 1 more comment

1 answer

0


The program was working for some, it also worked on an online compiler for me, but in the end I did a function to calculate the power. I just added this function and swapped Pow for calc_pow in the question code.

Thanks for trying to help, @anonimo @user140828

int calc_pow(int base, int exp)
{
  int pow_result = 1;

  for (int i = 1; i <= exp; i++)
    pow_result *= base;

  return pow_result;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.