【问题标题】:Reducing Fractions减少分数
【发布时间】:2014-06-08 07:33:14
【问题描述】:

我的代码:

Private Sub btnReduce_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnReduce.Click

    Call Reduce()

End Sub

Function Reduce() As Single

    Dim num As Integer = txtNum.Text
    Dim deno As Integer = txtDeno.Text

    For i = 1 To deno Step +1
        If num Mod i = 0 Then
            num = num / i
        End If

        If deno Mod i = 0 Then
            deno = deno / i
        End If

    Next

    lblOutputNum.Text = num
    lblOutputDeno.Text = deno

End Function

当我输入 2/4 时,它给了我 1/2。但是当我输入 3/6 时,它给了我 1/1。有谁知道它为什么这样做?因为我无法弄清楚这一点。感谢任何可以做到的人。

【问题讨论】:

  • 请考虑阅读以前版本的reduce fraction 问题中提供给您的链接。我没有看到链接 simplify fractoions 中建议的计算 GCD 的代码。
  • GCD 确实不是特定于语言的......GCD - 以及对应的Euclidean algorithm
  • 我还是不明白,我用的是欧几里得算法,什么都没用。

标签: vb.net fractions


【解决方案1】:

分子和分母不能相互独立,否则会改变分数的值:

For i = 1 To Math.Min(deno, num)/2 Step +1
    If num Mod i = 0 And deno Mod i = 0 Then
        num = num / i
        deno = deno / i
    End If
Next

请记住,这种方法的性能不是很好。您需要将分子和分母除以它们的最大公约数。 GCD可以用欧几里得算法计算。

【讨论】:

  • +1。正如昨天已经建议的那样,OP 似乎对使用 GCD 不感兴趣。
【解决方案2】:

使用 Nico 的示例,我设法进一步减少了分数。

For i = 1 To Math.Min(deno, num)/2 Step +1
 If num Mod i = 0 And deno Mod i = 0 Then
  num = num / i
  deno = deno / i
 End If
 If i > 1 Then
  While nume Mod i = 0 And deno Mod i = 0
   nume = nume / i
   deno = deno / i
  End While
 End If
Next

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-03
    • 1970-01-01
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多