-3
#include <iostream>
#include <math.h>

using namespace std;

int main() {
    int n, temp, rem, digits=0, sum=0;
    cout << "Enter a armstrong number: ";
    cin >> n;
    temp = n;
    digits = (int)log10(n) + 1;

    while (n != 0) {
        rem = n % 10;
        sum = sum + pow(rem, digits);
        n = n / 10;
    }

    if (temp == sum) {
        cout << "yes";
    }
    else {
        cout << "not";
    }
}

How does the " digits = (int)log10(n) + 1; " line actually calculates the digits? can anyone explain?

Chris
  • 26,361
  • 5
  • 21
  • 42
  • In C++, include `` rather than ``. – Chris Oct 14 '22 at 06:03
  • 1
    Do you know what the logarithms (to base 10) are for values like 10, 100, 1000, 10000? Do you know them for 50, 600, 7000? Do you know what happens if you cast those values into an `int`? What else do you need explained? – Yunnosch Oct 14 '22 at 06:06
  • 2
    Apart from that, using floating point functions and then expecting integer results (even after casting) can have some nasty surprises for you. – Yunnosch Oct 14 '22 at 06:08
  • https://en.wikipedia.org/wiki/Logarithm explains this property of logarithms at the very beginning. – hyde Oct 14 '22 at 06:12
  • *"How does the " `digits = (int)log10(n) + 1;` " line actually calculates the digits?..."* This is **more of a math question instead of programming question**. https://math.stackexchange.com/ – Jason Oct 14 '22 at 06:36
  • I was confused about the (int) part from the line . @JasonLiam – Shree Mahadik Oct 14 '22 at 15:35

1 Answers1

1

Math.

Logarithms are basically "exponents in reverse." Log10(100) is 2.0, as 10 to the second power is 100.

Cast to 'int and add one to that are you get 3, which is the number of digits.

Chris
  • 26,361
  • 5
  • 21
  • 42