Analysis: The definition of the narcissus number is the three-digit sum of the digits equal to the number itself.
We first need to create a loop that can output all three-digit numbers;
We also need to establish a judgment condition. Every time a number is output, judge whether it is a narcissus number. If it is, output it. If not, continue the loop without outputting it.
You also have to find a way to separate the three digits before you can make a judgment.
The source code is as follows and can be copied:
#include<stdio.h>
int main()
{
int number, a, b, c;
for(number=100;number<=999;number++)//输出所有的三位数
{
a = number / 100;//取得百位数
b = number % 100 / 10;//取得十位数
c = number % 10;//取得个位数
if (number == a * a * a + b * b * b + c * c * c)//判断是否为水仙花数
printf("%5d", number);
}
return 0;
}
Of course, the code is not unique, the following code is also possible:
#include<stdio.h>
int main()
{
int i, a, b, c;
for(i=100;i<1000;i++)
{
a = i / 100;
b = (i - a * 100) / 10;
c = i % 10;
if (a * a * a + b * b * b + c * c * c == i)
printf("%d ", i);
}
return 0;
}
If you want to output all the daffodil numbers on the form in the format of 2 numbers per line, then:
#include<stdio.h>
int main()
{
int i, a, b, c,n=0;
for(i=100;i<1000;i++)
{
a = i / 100;
b = (i - a * 100) / 10;
c = i % 10;
if (a * a * a + b * b * b + c * c * c == i)
{
printf("%d ", i);
n++;
if (n % 2 == 0)
printf("\n");
}
}
return 0;
}