分别使用while、do-while和for语句编程,找出所有的水仙花数并输出。

如题所述

For语句

public class numl {

public static void main(String[] args) {

int x, y, z, i, sum;

for(i=100;i<1000;i++)

z=i%100%10;

y=i/10;

y=y%10; 

x=i/ 100;

sum=x*x*x+y*y*y+z*Z*z;

if (sum=i)

System. out. println (sum+"是水仙花数”) ;

}

}

Whi le语句

public class numl {

public static void main(String[] args) {

int x, y, z, i=100, sum;

while(i<1000)

z=i%100%10;

y=i/10;

y=y%10;

x=i/ 100;

sum=x*x*x+y*y*y+z*z*z;

if(sum==i)

System. out. println(sum+”是水仙花数"); .

i++;

}

}

Do-whil e语句

public class numl {

public static void main(String[] args) {

int x, y, z, i=100, sum;

do{

z=i%100%10;

y=i/10;

y=y%10;

x=i/ 100;

sum= Fx*x*x+y*y*y+z*z*z;

if (sum=i)

System. out. println(sum+”是水仙花数”);

} while(i<1000) ;

}

扩展资料

do-while循环的与for循环,while循环的区别

一、循环结构的表达式不同

do-while循环结构表达式为:do{循环体;}。

for循环的结构表达式为:for(单次表达式;条件表达式;末尾循环体){中间循环体}。

while循环的结构表达式为:while(表达式){循环体}。

二、执行时判断方式不同

do-while循环将先运行一次,因为经过第一次do循环后,当检查条件表达式的值时,其值为 不成立时而会退出循环。保证了至少执行do{ }内的语句一次。

for循环执行的中间循环体可以为一个语句,也可以为多个语句,当中间循环体只有一个语句时,其大括号{}可以省略,执行完中间循环体后接着执行末尾循环体。

while循环执行时当满足条件时进入循环,进入循环后,当条件不满足时,执行完循环体内全部语句后再跳出(而不是立即跳出循环)。

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-06-16

C语言程序:

#include "stdio.h"

/* 使用while循环找出所有的水仙花数 */
void flower1()
{
int n;
int a, b, c;

n = 100;
while(n < 1000)
{
a = n / 100;
b = n / 10 % 10;
c = n % 10;
if(a*a*a + b*b*b + c*c*c == n)
printf("%d\n", n);
n++;
}
}

/* 使用do-while循环找出所有的水仙花数 */
void flower2()
{
int n;
int a, b, c;

n = 100;
do
{
a = n / 100;
b = n / 10 % 10;
c = n % 10;
if(a*a*a + b*b*b + c*c*c == n)
printf("%d\n", n);
n++;
} while(n < 1000);
}

/* 使用for循环找出所有的水仙花数 */
void flower3()
{
int n;
int a, b, c;

for(n=100; n<1000; n++)
{
a = n / 100;
b = n / 10 % 10;
c = n % 10;
if(a*a*a + b*b*b + c*c*c == n)
printf("%d\n", n);
}
}

void main()
{
printf("使用while循环找出的水仙花数\n");
flower1();

printf("使用do-while循环找出的水仙花数\n");
flower2();

printf("使用for循环找出的水仙花数\n");
flower3();
}


运行结果:

使用while循环找出的水仙花数
153
370
371
407
使用do-while循环找出的水仙花数
153
370
371
407
使用for循环找出的水仙花数
153
370
371
407

本回答被网友采纳
第2个回答  2011-12-23
100——1000内的水仙花数
首先是for:
int i,j,k,n;
for( n=100;n<1000;n++){
i=n/100;
j=(n%10)/10;
k=n%10;
if(n==i*i*i+j*j*j+k*k*k){
System.out.println(n);
}

}本回答被网友采纳
第3个回答  2012-04-10
dim i as integer,m as integer
for i=100 to 999
m=(i mod 10)^3 +(i \10 mod 10)^3+(i\100)^3
if m=i then print i
next i

Dim a%, b%, c%
For a = 1 To 9
For b = 0 To 9
For c = 0 To 9
If a ^ 3 + b ^ 3 + c ^ 3 = a * 100 + b * 10 + c Then
print a * 100 + b * 10 + c
End If
Next c
Next b
Next a
第4个回答  2011-12-23
水仙花数是无穷的 你给个范围 比方说三位的水仙花数,或者不到五位的之类。
相似回答