我有这样的代码,它试图显示;
然后;
以下是我到目前为止所拥有的:
Evennumber=InputBox("Please enter a even number!")
print "total + e"
For e= 2 to Evennumber step 2
total= total+e
print total&" + "&e
Next
print total
Oddnumber=InputBox("Please enter a odd number!")
print "total + o"
For o= 1 to Oddnumber step 2
total = total + o
print total&" + "&o
Next
print total这是正确的吗?
发布于 2019-01-15 09:38:57
关键是在使用total之前没有将它初始化为零。
Option Explicit
Dim e, o, Evennumber, Oddnumber, total
Evennumber = InputBox("Please enter a even number!")
MsgBox "total + e"
total = 0
For e = 2 to Evennumber step 2
total= total+e
MsgBox total & " + " & e
Next
MsgBox total
Oddnumber = InputBox("Please enter a odd number!")
MsgBox "total + o"
total = 0
For o = 1 to Oddnumber step 2
total = total + o
MsgBox total & " + " & o
Next
MsgBox total发布于 2019-01-15 13:52:13
@iBug的回答是正确的,但它没有指出您应该尝试遵循的重要编程原则,从长远来看,这些原则将使您受益。这个例子集中在干(不要重复)上,如果实现了这一点,total的重集就会变成零。
选择一个数字和按值遍历数字的两个过程几乎是相同的。当您有这样的代码时,最好的方法是构建一个函数或Sub过程来处理逻辑,而不需要重复它。
下面我们使用一个名为ProcessNumbers()的Sub过程,通过这种方式传递我们想要的偶数还是奇数,通过一些初始设置,我们可以使用相同的函数来处理这两组数字。
Option Explicit
'Even
Call ProcessNumbers(True)
'Odd
Call ProcessNumbers(False)
Sub ProcessNumbers(isEven)
Dim i, startFrom, endAt, total, label
Dim input, criteria
If isEven Then
startFrom = 2
endAt = 100
label = "Even"
Else
startFrom = 1
endAt = 100
label = "Odd"
End If
input = InputBox("Please enter an " & label & " number!")
If Len(input & "") > 0 And IsNumeric(input) Then endAt = CLng(input)
For i = startFrom To endAt
If isEven Then criteria = (i Mod 2 = 0) Else criteria = (i Mod 2 <> 0)
If criteria Then
total = total + i
WScript.Echo total & " + " & i
End If
Next
WScript.Echo total
End Sub输出:
2 + 2
6 + 4
12 + 6
20 + 8
30 + 10
42 + 12
56 + 14
72 + 16
90 + 18
110 + 20
132 + 22
156 + 24
182 + 26
210 + 28
240 + 30
272 + 32
306 + 34
342 + 36
380 + 38
420 + 40
462 + 42
506 + 44
552 + 46
600 + 48
650 + 50
702 + 52
756 + 54
812 + 56
870 + 58
930 + 60
992 + 62
1056 + 64
1122 + 66
1190 + 68
1260 + 70
1332 + 72
1406 + 74
1482 + 76
1560 + 78
1640 + 80
1722 + 82
1806 + 84
1892 + 86
1980 + 88
2070 + 90
2162 + 92
2256 + 94
2352 + 96
2450 + 98
2550 + 100
2550
1 + 1
4 + 3
9 + 5
16 + 7
25 + 9
36 + 11
49 + 13
64 + 15
81 + 17
100 + 19
121 + 21
144 + 23
169 + 25
196 + 27
225 + 29
256 + 31
289 + 33
324 + 35
361 + 37
400 + 39
441 + 41
484 + 43
529 + 45
576 + 47
625 + 49
676 + 51
729 + 53
784 + 55
841 + 57
900 + 59
961 + 61
1024 + 63
1089 + 65
1156 + 67
1225 + 69
1296 + 71
1369 + 73
1444 + 75
1521 + 77
1600 + 79
1681 + 81
1764 + 83
1849 + 85
1936 + 87
2025 + 89
2116 + 91
2209 + 93
2304 + 95
2401 + 97
2500 + 99
2500https://stackoverflow.com/questions/54192986
复制相似问题