【问题标题】:For next loop multiplying numbers对于下一个循环乘以数字
【发布时间】:2015-03-10 01:08:49
【问题描述】:

我正在尝试创建一个计算器,用户输入一个数字 (1-20),它让用户可以选择从 1 到他们输入的数字的总和或乘积。即 5 的总和为 15,而乘积为 120。我正在使用 select case 和 for next 循环。我设法让计算器的总和部分正常工作,并认为我可以对乘积部分使用相同的原理,但我没有这样的运气。任何帮助或在正确方向上的温和推动将不胜感激。 干杯。

代码:

    Dim intsum As Integer
    Dim intnum As Integer
    Dim intproduct As Integer

    If IsNumeric(txtinput.Text) Then
        intnum = CInt(txtinput.Text)
    Else
        MessageBox.Show("Please enter a numeric value", "Input error")
        txtinput.Clear()
        txtinput.Focus()

    End If

    If intnum >= 1 AndAlso intnum <= 20 Then

        Select Case True

            Case btnproduct.Checked
                For P = 1 To intnum Step 1
                    intproduct = intproduct * P

                Next


            Case btnsum.Checked
                For S = 1 To intnum Step 1
                    intsum = intsum + S
                Next




        End Select

【问题讨论】:

  • 我认为你需要将initproduct初始化为1。
  • 你需要在循环之前初始化 intproduct,上面的代码它会一直为零。
  • 您可能需要重新考虑您支持的值的范围。 20! = 2.432902e+18 不适合 Integer
  • 对于更广泛的微调,您可能需要查找 Enumerable.Range(但要注意第二个参数是计数,而不是最终值)、Enumerable.AggregateLambdas

标签: vb.net


【解决方案1】:

将 intproduct 初始化为 = 1,因为此时您将值乘以 0,因此最终结果将始终显示为 0。

【讨论】:

    【解决方案2】:

    如果值不是数字,则无需检查 intnum 的值。

    Dim intsum As Integer
    Dim intnum As Integer
    Dim intproduct As Integer
    
    If IsNumeric(txtinput.Text) Then
        intnum = CInt(txtinput.Text)
    
        If intnum >= 1 AndAlso intnum <= 20 Then
    
            Select Case True
    
            Case btnproduct.Checked
                For P = 1 To intnum Step 1
                    intproduct = intproduct * P
    
                Next
    
    
            Case btnsum.Checked
                For S = 1 To intnum Step 1
                    intsum = intsum + S
                Next
    
    
    
    
            End Select
        End If 
    Else
        MessageBox.Show("Please enter a numeric value", "Input error")
        txtinput.Clear()
        txtinput.Focus()
    
    End If
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多