求帮我找这个VB程序里的错误
程序目的就是自己设定上下限,然后在这之间找出所有水仙花数,水仙花数就是像153=1^3+5^3+3^3,407=4^3+0^3+7^3这样的数
代码如下:Private Sub Command1_Click()
Text1.Text = ""
Dim i%, b%, c%, x%, y%, s As String
x = Val(Text2)
y = Val(Text3)
For i = x To y
For j = 1 To Len(i)
a = Mid(i, j, 1)
b = b + a ^ 3
Next j
c = Mid(i, 1, 1)
If i = b Then
s = s & i & "=" & c & "^3"
For m = 2 To Len(i)
n = Mid(i, m, 1)
s = s & "+" & n & "^3"
Next m
Text1.Text = s
End If
Next i
End Sub
追问:sFactor = Mid(sFactor, 4)
这条语句是干嘛的,没看懂
答案:错误太多了,Len(i) 是一个错误
'========================================================================
我给你另外写段代码吧
Private Sub Command1_Click()
'本程序由 “々霭圪巫师◎” 写给问问网友的demo
'あいしてるLY - Laser
'本程序完成完成于2011-7-21
Dim nBegin As Long, nEnd As Long
Dim st As String, sR As String, sFactor As String
Dim it As Integer, iR As Long
nBegin = Val(Text2.Text)
nEnd = Val(Text3.Text)
For i = nBegin To nEnd
st = CStr(i)
iR = 0
sFactor = ""
For j = 1 To Len(st)
it = Mid(st, j, 1)
iR = iR + it ^ Len(st)
sFactor = sFactor & " + " & CStr(it) & "^" & Len(st)
Next
If i = iR Then
sFactor = Mid(sFactor, Len(" + "))
sR = sR & st & " = " & sFactor & vbCrLf
End If
Next
Text1.Text = sR
End Sub
Private Sub Form_Load()
Me.Caption = "求水仙花数 "
End Sub
'=======================================================================
为了提高速度,我再次完善了代码
Private Sub Command1_Click()
'本程序由 “々霭圪巫师◎” 写给问问网友的demo
'あいしてるLY - Laser
'本程序完成完成于2011-7-21
Dim nBegin As Long, nEnd As Long
Dim Num() As Integer, iCount As Integer
Dim sNum As String, sResult As String, sFactor As String
Dim lSum As Long
nBegin = Val(Text2.Text)
nEnd = Val(Text3.Text)
If nBegin < 100 Then
MsgBox "水仙花数是一个大于或等于三位的数 ", vbExclamation, "请注意"
ElseIf nEnd < nBegin Then
MsgBox "末尾数必须大于起始数", vbExclamation, "请注意"
Else
For i = nBegin To nEnd
sNum = CStr(i)
iCount = Len(sNum)
ReDim Num(1 To iCount)
lSum = 0
For j = 1 To iCount
Num(j) = Val(Mid(sNum, j, 1))
lSum = lSum + Num(j) ^ iCount
Next
If i = lSum Then
sFactor = ""
For j = 1 To iCount
sFactor = sFactor & " + " & CStr(Num(j)) & "^" & CStr(iCount)
Next
sFactor = Mid(sFactor, 4)
sResult = sResult & sNum & " = " & sFactor & vbCrLf
End If
Next
Text1.Text = sResult
End If
End Sub
Private Sub Form_Load()
Me.Caption = "求水仙花数 "
End Sub
修改代码如下:
Option Explicit
Private Sub Command1_Click()
Dim i As Long
Dim a As String, b As String
a = Text1.Text
b = Text2.Text
For i = Val(a) To Val(b)
Dim k As String, h As Long, j As Integer, n As Integer
n = Len(Str(i)) - 1 '解释1,2
For j = 1 To n
k = Mid(i, j, 1)
h = h + Val(k) ^ n '注意2
Next j
If h = i Then
Dim u As String, s As String
u = Mid(i, 1, 1)
s = i & "=" & u & "^" & n
For j = 2 To n
k = Mid(i, j, 1)
s = s & "+" & k & "^" & n
Next j
Print s
End If
s = ""
h = 0
Next i
End Sub
您需要注意以下几点:
1.水仙花数的位数>=3;
2.不能都以3次方的方法计算; 通俗说就是:水仙花数的位数是几位,次幂就是几次!
如4位水仙花数1634=1^4+6^4+3^4+4^4;
如6位水仙花数548834=5^6+4^6+8^6+8^6+3^6+4^6;
解释1: 若n为字符串,Len(n)返回n字符串内字符数目;
若n为变量名,Len(n)返回n类型数值在内存中所占字节数;
如:Dim n as String Dim n as Long
n="aaabbb" n=123456
Print Len(n) &nb
上一个:求一VB高手,帮忙添加一个自动拨号功能
下一个:用VB编程 “儿童认识钟表” 约50行