求水仙花数(C语言/Java)

匿名 (未验证) 提交于 2019-12-02 21:52:03

求出0~999999之间的所有“水仙花数”并输出。
“水仙花数”是指一个三位数,其各位数字的立方和确好等于该数本身,
如:153=1 ^ 3+5 ^ 3+3 ^ 3 ? ,则153是一个“水仙花数”。

C语言程序:

int main() {  int i = 0;  for (i = 0; i < 1000000; i++)  {   int count = 1;   int tmp = i;//11   int sum = 0;   //计算几位数   while (tmp / 10)//10 11   {    count++;//2    tmp /= 10;//1   }   //计算每位数的次方和   tmp = i;//10   while (tmp)   {    sum +=pow(tmp % 10, count);//pow(a,b)函数计算a的b次方的值,头文件 math.h    tmp = tmp / 10;   }   //比较   if (i == sum)    printf("%d ", i);  }  system("pause");  return 0; } 

Java程序:

public class Text {     public static void main(String[] args) {         int i = 0;                     for (i = 0; i <= 999; i++) {             int temp = i;             //double sum = 0;               //判断位数:10~99 只判断一次10 三位数只判断一次100              //10%10==0;100%10==0,但中间会有20%10==0所以就有              //20/10=2(20>>1),30/10=3;10/10=1(10>>1),100/10=10(100>>1)              //所以 就要加一个条件使20,30...不能进循环,让10和100要进循环             int count = 1;  //存储一个数的位数                        //int j = 0;             //while (((temp % 10) == 0) && ((temp / 10) == (Math.pow(10,j)))) {                         while (temp / 10 != 0){                 count++;                 temp /= 10;                // j++;                        }              // System.out.println(count);                    //求余进行判断             // int a = i % 10;             // int b = (i / 10) % 10;             // int c = (i / 100);             // if (i == Math.pow(a,count) + Math.pow(b, count) + Math.pow(c, count)) {             //     System.out.print(i + " ");             // }                            }     } }  
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!