温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java实现水仙花数的计算

发布时间:2020-09-23 16:39:40 来源:脚本之家 阅读:339 作者:隔世离空的风景 栏目:编程语言

看到标题java实现水仙花数,首先先要知道什么是水仙花数,具体了解一下

所谓“水仙花数”是指一个三位数,其各位数字立方和等于该数

列如153=1*1*1+5*5*5+3*3*3  那么153就是水仙花数,首先是分析需要的功能,首先他是一个3位数。

那值一定在100-1000之间,必定要用到循环。可用for循环,while循环,do while 循环,其次是它需要满足条件

“其各位数字立方和等于该数”,那么我们必须把他的各位的数字取出。我们在循环里做判断,当数满足条件就将这个数取出。

那么可做出如下流程图。

java实现水仙花数的计算

根据流程图,可得如下代码。代码几种循环的方法都用的了。

package com.tjgx.lxb;
/*要求:100--1000的水仙花数
 * 水仙花定义:水仙花数”是指一个三位数,其各位数字立方和等于该数
 * **/
public class Daffodils {
 public static void main(String[] args) {
 System.out.println("用dowhile循环方法");
 demo1();
 System.out.println("用for循环方法");
 demo2();
 System.out.println("用while循环方法");
 demo3();
 
 
 }
 
 //用dowhile 循环来做
public static void demo1() {
 int i=100;
 do{
 int g=i%10; //取出个位数
 int s=i/10%10; //取出十位数
 int b=i/100; //取出百位数
 if(g*g*g+s*s*s+b*b*b==i) {
 System.out.println(i+"是水仙花数");
 } 
 i++; 
 }while(i<1000);
 }
 //用for循环来做
public static void demo2() {
 for(int j=100;j<1000;j++) {
 int g=j%10; //取出个位数
 int s=j/10%10; //取出十位数
 int b=j/100; //取出百位数
 if(g*g*g+s*s*s+b*b*b==j) {
 System.out.println(j+"是水仙花数");
 } 
 }
 }
//用while循环来做
public static void demo3() {
 int k=100;
 while(k<1000) {
 int g=k%10; //取出个位数
 int s=k/10%10; //取出十位数
 int b=k/100; //取出百位数
 if(g*g*g+s*s*s+b*b*b==k) {
 System.out.println(k+"是水仙花数");
 } 
 k++;
 
 }
 }
 
}

运行结果如下图

java实现水仙花数的计算

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI