分别使用while、do-while和for语句编程,找出所有的水仙花数并输出。
答案:4 悬赏:60 手机版
解决时间 2021-03-17 09:57
- 提问者网友:活着好累
- 2021-03-16 16:59
分别使用while、do-while和for语句编程,找出所有的水仙花数并输出。
最佳答案
- 五星知识达人网友:毛毛
- 2021-03-16 17:37
C语言程序:
#include "stdio.h"
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++;
}
}
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++;
} while(n < 1000);
}
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);
}
}
void main()
{
printf("使用while循环找出的水仙花数
");
flower1();
printf("使用do-while循环找出的水仙花数
");
flower2();
printf("使用for循环找出的水仙花数
");
flower3();
}
运行结果:
使用while循环找出的水仙花数
153
370
371
407
使用do-while循环找出的水仙花数
153
370
371
407
使用for循环找出的水仙花数
153
370
371
407
#include "stdio.h"
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++;
}
}
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++;
} while(n < 1000);
}
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);
}
}
void main()
{
printf("使用while循环找出的水仙花数
");
flower1();
printf("使用do-while循环找出的水仙花数
");
flower2();
printf("使用for循环找出的水仙花数
");
flower3();
}
运行结果:
使用while循环找出的水仙花数
153
370
371
407
使用do-while循环找出的水仙花数
153
370
371
407
使用for循环找出的水仙花数
153
370
371
407
全部回答
- 1楼网友:刀戟声无边
- 2021-03-16 21:41
水仙花数是无穷的 你给个范围 比方说三位的水仙花数,或者不到五位的之类。
- 2楼网友:轮獄道
- 2021-03-16 20:06
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
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
- 3楼网友:轮獄道
- 2021-03-16 18:44
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);
}
}
首先是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);
}
}
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯