当然,在做题之前,你要知道什么是 水仙花 数
水仙花数:也称为--阿姆斯特朗数,是指一个n位数,其各位数字的n次幂之和等于该数本身。
例如,1^3 + 5^3 + 3^3 = 153,153就是一个水仙花数。
源代码如下
#include <stdio.h>
int main() {
int hundreds,tens,units;
int i,count=0;
for(i=100; i<=999; i++) {
hundreds = i / 100;
tens = (i / 10) % 10;
units = i % 10;
if (hundreds * hundreds * hundreds + tens * tens * tens + units * units * units == i) {
printf("%d ", i);
count++;
}
}
printf("水仙花个数为:%d",count);
return 0;
}
首先,第一行的头文件肯定不能少,基本框架也是
#include <stdio.h>
int main() {
return 0;
}
然后定义百位、十位和个位上的数,为了好理解,我就将其分别用英文分两行表示
其中的 i 是循环时用的,而 count 为了计算其个数,赋给初值为 0 。
int hundreds,tens,units;
int i,count=0;
下面是循环,因为是从 100 到 999 ,所以将 i 的初值为 100 ,到 999 结束,然后 i 自增
for(i=100; i<=999; i++) {
}
然后分别将个位、十位、百位上的数取出,赋给刚刚定义的个位、十位和百位
hundreds = i / 100;
tens = (i / 10) % 10;
units = i % 10;
然后就是最重要的一步,因为我们没有加数学函数,所以我们只能用笨一点的方法去判断条件了(当然,如果你加了数学函数,也可以用pow()来给予次幂)
if (hundreds * hundreds * hundreds + tens * tens * tens + units * units * units == i)
然后就是在这个分支里面进行的输出和计数(满足条件输出,同时count自增计数)
printf("%d ", i);
count++;
最后在编程结尾处输出总数(即count共自增了几次)然后给予温馨的文字提示
printf("水仙花个数为:%d",count);
最后 return,编程结束
(如果你真的想用数学函数,那我就把代码放下面吧,省的你们在去找了)
#include <stdio.h>
#include <math.h>
int main() {
int hundreds,tens,units;
int i,count=0;
for(i=100; i<=999; i++) {
hundreds = i / 100;
tens = (i / 10) % 10;
units = i % 10;
if (pow(hundreds,3) + pow(tens,3) + pow(units,3)== i) {
printf("%d ", i);
count++;
}
}
printf("水仙花个数为:%d",count);
return 0;
}
7017

被折叠的 条评论
为什么被折叠?



