本文主要是介绍求出0~999之间的所有“水仙花数”并输出。(“水仙花数”是指一个三位数,其各位数字的立方和确好等于该数本身),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
方法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;
}
这篇关于求出0~999之间的所有“水仙花数”并输出。(“水仙花数”是指一个三位数,其各位数字的立方和确好等于该数本身)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!