我需要一些幫助才能使此代碼正常作業。我需要代碼來計算前 100 個偶數和奇數。下面的代碼顯示了偶數部分,但我認為它們的作業方式相同,只是數字不同。我知道前 100 個偶數是 2 到 200 或 0 到 200?,而前 100 個奇數是 1 到 199。(我還需要使用 while 回圈,我會使用單獨的 while 回圈來確定代碼如何計算總和?)
這是代碼。
Dim sum, count As Integer 'the sum and count are changing and they must be a whole number.
Const num As Integer = 2
'now we must deveolp a while loop/equation that adds every number lower or equal to 100 together.
While count Mod 2 <= 200 'while the count is smaller or equal to 100,
count =
sum = count 'The sum will be add or equaled to the count
count = 1 'The count will be added to equaled to 1
End While
Console.WriteLine("The Sum of the first 100 even numbers is: {0}!", sum) 'This is the text the user sees, which tells them that the sum of the first 100 numbers will be 5050.
Console.ReadLine()
End Sub
像往常一樣,數學部分給我帶來了麻煩。我覺得我的想法是正確的,但我無法正確執行它。
uj5u.com熱心網友回復:
您可以在一個回圈中同時計算這兩個值:
Dim maxCount = 100
Dim sumEven, sumOdd, countEven, countOdd As Integer
Dim number = 0
While countEven < maxCount OrElse countOdd < maxCount
If number Mod 2 = 0 Then
countEven = 1
sumEven = number
Else
countOdd = 1
sumOdd = number
End If
number = 1
End While
所以While回圈收集偶數和奇數,直到找到 100。If檢查數字是否可以除以 2。 = number計算所有偶數和奇數的總和,然后 = 1簡單地計算它們。
uj5u.com熱心網友回復:
Dim sumEven, sumOdd As Integer
Dim even = 2
Dim odd = 1
While even <= 200 AndAlso odd <= 200
sumEven = even
sumOdd = odd
even = 2
odd = 2
End While
Console.WriteLine("The Sum of the first 100 even numbers is: {0}!", sumEven)
Console.WriteLine("The Sum of the first 100 odd numbers is: {0}!", sumOdd)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/320885.html
上一篇:Html按鈕打樁
