How to use a for loop to find Armstrong numbers in C++?
A narcissistic number is an n-digit number that is equal to the sum of each digit raised to the power of n. For example, 153 is a narcissistic number because 1^3 + 5^3 + 3^3 = 153.
Here is an example code using a for loop to find Armstrong numbers.
#include <iostream>
#include <cmath>
int main() {
int num, n, digit, sum;
for(num = 100; num < 1000; num++) {
n = 0;
sum = 0;
int temp = num;
// 计算num的位数
while(temp != 0) {
temp /= 10;
n++;
}
temp = num;
// 求每个位上的数的n次幂之和
while(temp != 0) {
digit = temp % 10;
sum += pow(digit, n);
temp /= 10;
}
// 判断是否是水仙花数并输出
if(num == sum) {
std::cout << num << " ";
}
}
return 0;
}
This code will print all three-digit Armstrong numbers, such as 153, 370, 371, 407. You can modify the range and number of digits in the loop to calculate Armstrong numbers with different digits as needed.