【问题标题】:Sum of the first 100 even and odd number?前100个偶数和奇数之和?
【发布时间】:2021-12-04 21:55:57
【问题描述】:

我需要一些帮助才能使此代码正常工作。我需要代码来计算前 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

像往常一样,数学部分给我带来了麻烦。我觉得我有正确的想法,但我无法正确执行。

【问题讨论】:

    标签: vb.net visual-studio visual-studio-code


    【解决方案1】:
        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)
    

    【讨论】:

    • 非常感谢,即使我将偶数和奇数部分分开,您的代码也能正常工作,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多