方法1.for循环
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i = 0;
int count = 0;
printf("水仙花数有:\n");
for (i = 100; i < 1000; i++)
{
int bai = i / 100;
int shi = i / 10 - bai * 10;
int ge = i % 10;
if (i == (bai*bai*bai + shi*shi*shi + ge*ge*ge))
{
count++;
printf("%d\n", i);
}
}
printf("水仙花数有:%d个\n", count);
system("pause");
return 0;
}
方法2.while循环
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i = 100;
int count = 0;
printf("水仙花数有:\n");
while (i < 1000)
{
int bai = i / 100;
int shi = i / 10 - bai * 10;
int ge = i % 10;
if (i == (bai*bai*bai + shi*shi*shi + ge*ge*ge))
{
count++;
printf("%d\n", i);
}
i++;
}
printf("水仙花数有:%d个\n", count);
system("pause");
return 0;
}
方法3.do...while循环
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i = 100;
int count = 0;
printf("水仙花数有:\n");
do
{
int bai = i / 100;
int shi = i / 10 - bai * 10;
int ge = i % 10;
if (i == (bai*bai*bai + shi*shi*shi + ge*ge*ge))
{
count++;
printf("%d\n", i);
}
i++;
} while (i < 1000);
printf("水仙花数有:%d个\n", count);
system("pause");
return 0;
}
优化:数不限大小
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int i = 0;
printf("水仙花数有:\n");
for (i = 1; i < 1000000; i++)
{
//计算i的位数
int count = 1;
int tmp = i;
while (tmp / 10)
{
count++;
tmp = tmp / 10;
}
//拿到每一位,计算次方和
tmp = i;
int sum = 0;
while (tmp)
{
sum += pow(tmp % 10, count);
tmp = tmp / 10;
}
if (i == sum)
{
printf("%d ", i);
}
}
system("pause");
return 0;
}