我的代码:
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。有谁知道为什么这样做?我无法弄清楚这一点。感谢任何可以的人。
答案 0 :(得分:2)
你不能将分子和分母彼此独立地划分,否则你将改变分数的值:
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 :(得分:0)
使用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