在视觉基础中划分时丢失小数

时间:2017-04-27 21:19:42

标签: vb.net

我必须在visual basic中创建一个随机数学生成器,当用户选择除法时,它应该将数字显示为第二个小数。到目前为止,我所尝试过的任何事情都在不断完善。 选项严格要求

这是我到目前为止的代码

Private Sub DivisionProblem()
    ' Divide two numbers and display the answer
    Dim numSmallestNum As Integer = CreateANumber()
    Dim numLargestNum As Integer = CreateANumber()
    Dim strToWork As String


    If (numLargestNum > numSmallestNum) Then
        strToWork = (Convert.ToString(numLargestNum) & " / " & Convert.ToString(numSmallestNum))
        lblToWork.Text = strToWork

        _decAnswer = CInt((Decimal.Round(CDec(numLargestNum / numSmallestNum), 2)))

    Else
        strToWork = (numSmallestNum & " / " & numLargestNum)
        lblToWork.Text = strToWork
        _decAnswer = CInt((Decimal.Round(CDec(numSmallestNum / numLargestNum), 2)))
    End If
End Sub

如果有人有任何建议我会非常感激。谢谢!

4 个答案:

答案 0 :(得分:3)

CInt强制该值为Integer而不是Double。

答案 1 :(得分:2)

Dim numSmallestNum As Integer = CreateANumber()
Dim numLargestNum As Integer = CreateANumber()

声明这两个As Decimal,并且无需转换任何内容。

答案 2 :(得分:1)

您希望Dim _decAnswer as Decimal并使用CDec代替CInt

有关Decimal类型的其他背景信息,check out this article

您可能还需要考虑使用DoubleCDbl代替DecimalCDec,具体取决于您的使用情况。

答案 3 :(得分:0)

据我所知,Integer不能保存小数。使用Dim ... As Decimal。只是让生活更轻松