
程序代码如下:
Private Sub Command1_Click()
Dim i As Integer, s As Integer
Dim a As Integer, b As Integer, c As Integer
Print "100到999所有水仙花数(也叫梅花数):"
For i = 100 To 999
a = i \ 100 '取百位数
b = i \10 Mod 10 '或 b = i Mod 100 \10 取十位数
c = i Mod 10 ‘取个位数
s = a ^ 3 + b ^ 3 + c ^ 3 '水仙花数的判断依据
If s = i Then
Print i
End If
Next i
End Sub
运行结果:
100到999所有水仙花数(也叫梅花数): 153 370 371 407
代码为:
using System
using System.Collections.Generic
using System.Text
namespace _
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("一重循环判断:")
Console.WriteLine("水仙花数有:")
int i,j, k, l
for (i = 100i <1000i++)
{
j = i / 100
k = i %100/10
l = i % 10
int n = j * j * j + k * k * k + l * l * l
if (n == i)
Console.WriteLine(n)
}
Console.WriteLine("三重循环判断:")
Console.WriteLine("水仙花数有:")
int q, w, e, r
for(q=1q<=9q++)
for(w=0w<=9w++)
for (e = 0e <= 9e++)
{
int s = q * 100 + w * 10 + e
int t = q * q * q + w * w * w + e * e * e
if (s == t)
Console.WriteLine(s)
}
}
}
}
扩展资料:注意事项
自定义函数is(number)判断number的各位数字立方和是否等于它本身,如is(121)返回值0,is(153)返回值1。 主函数输入两个正整数m和n(m>=1, n<=1000),输出m-n之间的所有满足各位数字和等于它本身的数。
Input
多组测试数据,每组输入两个正整数m和n(m>=1, n<=1000)。
Output
输出m-n之间的所有满足各位数字立方和等于它本身的数,空格隔开(最后一个数后无空格)。
Sample Input
1 100
50 200
50 500
Sample Output
1
153
153 370 371 407
#include<stdio.h>
#include<math.h>
int is(int number)
{
int s,sum=0
while(number!=0)
{
s=number%10//不断取余,直至为0
sum+=pow(s,3)
number=number//10不断去尾,直至为0
}
return sum
}
int main(void)
{
int m,n,k,flag
while(scanf("%d%d",&m,&n)!=EOF)
{
flag=1
for(k=mk<=nk++)
{
if(k==is(k))
{
if(flag!=0)
{
printf("%d",k)
flag=0
}
else
printf(" %d",k)
}
}
printf("\n")
}
return 0
}
这个程序在VB中与VC中是有些些不同的,因为VC中当定义每位为整型时,它不会有四舍五入规则的,而VB中则不同。比如:VC中(153/100)%10=1,而VB中它算出来的为2,所以注意这个就可以了。在VB中就先从个位判断,是否超过或等于5,是的话就让它减去0.5,不是的话直接 *** 作。VB中程序如下:一个按钮,一个标签就可以了。
Dim m As Integer
Dim m1 As Integer
Dim m2 As Integer
Dim m3 As Integer'm,m1,m2,m3最好是分开定义不然会出现ByRef参数类型不符的错误
Dim str As String
Private Sub Command1_Click()
For m = 100 To 999
m3 = m Mod 10
If m3 >= 5 Then
m2 = (m / 10 - 0.5) Mod 10 '因为当个位数大于5时,m/10会进一位,即十位会比原来的数据多1,所以要把这个四舍五入的位取消五入规则
Else
m2 = (m / 10) Mod 10
End If
If m2 >= 5 Then
m1 = m / 100 - 0.5 '原因同上
Else
m1 = m / 100
End If
If ((cubic(m1) + cubic(m2) + cubic(m3)) = m) Then
str = str + CStr(m) + vbCrLf '把每计算出的数据存到str中,并换行
Label2.Caption = str
End If
Next m
End Sub
Function cubic(data As Integer) As Double
cubic = data * data * data
End Function
结果如下图:
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)