Visual Basic将一个变量的内容从一个sub传递给另一个sub并舍入到d.p

时间:2018-04-12 16:09:24

标签: vb.net visual-studio

我创建了一个子,在输入3个系数后计算出二次方程。

但是,我必须将答案舍入到用户希望的1小数点到5之间。

Module Module1
Public property MyAnswer As Object
Sub myQuadraticEquation()
... 'enter 3 coefficients
Dim d As Integer = b ^ 2 - 4 * a * c 
    Console.Write("Your roots are: ")
    MyResult = (((-b + d) / (2 * a) & " , " & (-b - d) / (2 * a)))
    Console.WriteLine(MyAnswer)
End Module

我的问题是,如何根据用户的喜好将这个数学特征的答案四舍五入到一定数量的d.p?

我可以创建另一个sub,然后使用Quadratic方程中的if语句稍后调用它吗?

它给了我以下错误

  

“System.FormatException:'输入字符串的格式不正确。'

1 个答案:

答案 0 :(得分:0)

我建议总是将变量声明为您想要的数据类型,而不是依赖程序在运行时计算出来。因此,将Public property MyAnswer As Object更改为Public property MyAnswer As String。因为你知道你期望MyAnswer在最后成为一个字符串。

就四舍五入而言,我相信你试图这么做太晚了。我会改变

MyAnswer = (((-b + d) / (2 * a) & " , " & (-b - d) / (2 * a)))

Dim part1 As Decimal = Math.Round((-b + d) / (2 * a), DigitsToRound)
Dim part2 As Decimal = Math.Round((-b - d) / (2 * a), DigitsToRound)
'This line can be simplified, look up string interpolation if you are using  VS 2017
MyAnswer = part1 & " , " & part2

用户以某种方式指示DigitsToRound。更多的代码,从技术上讲可以简化一点,但我试图尽可能明确。

**编辑:

刚才意识到您的代码中存在名称差异。我假设您在发布的代码段中表示MyAnswer而不是MyResult。如果我弄错了,那么我就会大肆宣传。

**编辑#2:

  

如何将这些变量的内容转移到另一个子中,这样当我调用另一个sub时,我可以将它舍入到我想要的任何d.p。例如“你想把它变成3.d.p”......那么它应该在3dp中输出答案。我试过这样做,但我倾向于得到0作为输出

使用单独的函数似乎有点矫枉过正,但它可能看起来像这样:

Public Function DoRounding(ByVal p_value as Decimal) as Decimal 
    Dim ret As Decimal = 0D
    Dim DigitsToRound As Integer = 0
    'This line prompts the user for input and attempts to parse the input into an integer field named DigitsToRound. 
    'If the parsing fails then whatever the user typed in was not an integer and we tell them we are unable to proceed. Default input is 1.
    If Integer.TryParse(InputBox("How many digits would you like to round to?", "Decimal Places", 1), DigitsToRound) Then
        ret = Math.Round(p_value, DigitsToRound)
    Else
        MessageBox.Show("Invalid Input Detected")
    End If
    Return ret
End Function

这会在每次调用函数时提示用户,这可能非常烦人。最好提示它们一次,然后将它们输入的值传递给任何需要它的函数。

相关问题