-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.
– Andre
@user140828 gives me the wrong result, the function returns 0. (I will edit the question)
– Edi Junior
Here it worked for: 93084, 8208, 1634, 407, 371, 370 and 153.
– anonimo
Looks like it’s my compiler so I’ll try to reinstall it. Tested with gcc? @anonimo
– Edi Junior
You can also use some online compiler like ideone: https://ideone.com/
– anonimo
It worked perfectly in gcc. gcc version 7.4.0 (Ubuntu 7.4.0-1ubuntu1~18.04.1)
– anonimo