-1

So, I am creating a mathematical program, it has a couple of functions, one of the function is a decimal place holder, what this is:

the user is asked how many decimal places he would like his answers to be shown for the different mathematical solvers, so example is if he says 3 then my answer for another function e.g 1+1 would equal 2.000

They are asked a range between 1 and 5, I have the code for this but do not know how to implement it for the answer of the functions

'Decimal place

Sub Accuracy()

Line1: 
Dim DP Console.WriteLine("Please Enter the Decimial Limit between 1-5: ") DP = Double.Parse(Console.ReadLine()) If (DP > 5) Then Console.WriteLine("Error, Decimial Limit is between 1 and 5, Please Try Again!") GoTo Line1

Else
    DP = DP
    Console.Write("Decimial Limit has been Set Succuesfully to " & DP & " Decimal Places")
End If
End Sub

'Quadratic Equation

Sub QuadraticFunction() Dim a, b, c As Integer Dim d, x1, x2 As Double

line1:

Console.WriteLine("Please Input a Non-Zero Number, A: ")
a = Console.ReadLine()
If (a = 0) Then
    Console.WriteLine("Error, Number must not be 0, Try Again!")
    GoTo line1
End If
Console.WriteLine("Please Input The Value of, B: ")
b = Console.ReadLine()

Console.Write("Please Input the Value of, C: ")
c = Console.ReadLine()

d = b * b - (4 * a * c)
If (d = 0) Then

    Console.WriteLine("Both Roots Are Equal.")
    x1 = -b / (2.0 * a)
    x2 = x1
    x1 = Math.Round(x1, DP)
    x2 = Math.Round(x1, DP)
    Console.WriteLine("First Root, (Root1) = {0}", x1)
    Console.WriteLine("Second Root, (Root2) = {0}", x2)

ElseIf (d > 0) Then

    Console.WriteLine("Both Roots are Real and Different")

    x1 = (-b + Math.Sqrt(d)) / (2 * a)
    x2 = (-b - Math.Sqrt(d)) / (2 * a)


    x1 = (Math.Round(x1, DP))
    x2 = (Math.Round(x2, DP))

    Console.WriteLine("First Root, (Root1) = {0}", x1)
    Console.WriteLine("Second Root, (Root2) = {0}", x2)

Else

    Console.Write("Root are Imaginary " & "No Solution")
End If

End Sub

  • Are you asking how to **display** the values with a given number of decimal places, or how to **round** the values to a given number of decimal places? The existing answers deal with displaying the values. Look at the `Math.Round` method for how to round a value to a given number of decimal places. – Blackwood Feb 18 '19 at 20:24
  • Let me explain clearly: So there is a menu, function 1 is this decimal place calculator, The user is asked about how many decimal places would he like his answer to output for other functions, so let say 4. he is then redirected to the menu and he chooses the function he wants to use, lets say a simple addition, he inputs the value for a and b, so let say a = 5 and b = 7 as this is addition the answer = 12, however as he defined 4 as his decimal place option his answer should display 12.0000 –  Feb 18 '19 at 20:26
  • Then the existing answers will do what you want. For example, using Andrew Morton's code, create an Integer called `decimalPlaces` and set its value to 5. Now if `x2` has the value of 12, `String.Format("{0:F" & decimalPlaces & "}", x2)` will return "12.00000". – Blackwood Feb 18 '19 at 20:33
  • Yes but the user sets the decimal place by the option, please read the full code, I have attached –  Feb 18 '19 at 20:36
  • So store the number of decimal places that the user enters in the variable called `decimalPlaces`. make sure that variable is accessible to the code that will display the output. – Blackwood Feb 18 '19 at 20:37
  • You are using DP as your decimal places, however, you declare the variable inside of the Accuracy subroutine. You need to move the `Dim DP` outside of the sub declaration so that it is saved in your module level code. – IAmNerd2000 Feb 18 '19 at 20:38
  • Where would it go? –  Feb 18 '19 at 20:40
  • I tried declaring it as function instead, still getting same result –  Feb 18 '19 at 20:42
  • If you have a class declaration then it should go under that, but above any sub declaration. same if you have a module. Here is an article on [Scope](https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/declared-elements/scope) – IAmNerd2000 Feb 18 '19 at 20:45
  • @IAmNerd2000 still do not know, I have tried to look on Scope, still don't understand, The only code above this is the main menu, below it is the Quadratic Equation Function –  Feb 18 '19 at 20:52
  • I will post an example in my answer – IAmNerd2000 Feb 18 '19 at 20:55
  • @IAmNerd2000 Thank you, been stuck for this many days now! –  Feb 18 '19 at 21:01
  • @IAmNerd2000 ive tried your example, still not working. –  Feb 19 '19 at 10:51

2 Answers2

2

Nowadays it is usual to avoid GoTo statements as they can make following and maintaining the code difficult.

You can instead use various looping structures, for example:

Option Infer On
Option Strict On

Module Module1

    Dim decimalPlaces As Integer = 2 ' default value

    Sub Accuracy()
        Dim validEntry = False

        Do
            Console.Write("Please enter the decimal limit between 1-5: ")
            Dim a = Console.ReadLine()

            If Integer.TryParse(a, decimalPlaces) Then
                validEntry = decimalPlaces >= 1 AndAlso decimalPlaces <= 5
            End If

            If Not validEntry Then
                Console.WriteLine("Error: value must be an integer from 1 to 5.")
            End If

        Loop Until validEntry

        Dim plural = ""
        If decimalPlaces <> 1 Then plural = "s"
        Console.Write("Decimal limit has been set succesfully to " & decimalPlaces & " decimal place" & plural)

    End Sub

    Sub QuadraticFunction()
        ' other code...
        Console.WriteLine(String.Format("First Root, (Root1) = {0:F" & decimalPlaces & "}", x1))
        ' other code...

    End Sub

    Sub Main()
        ' code ....

    End Sub

End Module

You can use a standard numeric format string: The Fixed-Point ("F") Format Specifier which would be, say, "F2" for two decimal places, to format the output, for example:

Console.WriteLine("0.123456 to " & decimalPlaces & "D.P. is " & String.Format("{0:F" & decimalPlaces & "}", 0.123456))

Using a separate variable to read the user input into means that it would be easy to, say, add an option for them to enter "q" to quit.

I put in code to make "place" plural when needed: it makes the output neater.


[Incidentally, the free Visual Studio 2017 Community Edition is available for Windows 7 and later. It has things like "string interpolation" which can make formatting output easier.]

Andrew Morton
  • 24,203
  • 9
  • 60
  • 84
  • @Jaspal Are you only looking for the `String.Format("{0:F" & decimalPlaces & "}", x1)` part? – Andrew Morton Feb 18 '19 at 19:17
  • Let me explain clearly: So there is a menu, function 1 is this decimal place calculator, The user is asked about how many decimal places would he like his answer to output for other functions, so let say 4. he is then redirected to the menu and he chooses the function he wants to use, lets say a simple addition, he inputs the value for a and b, so let say a = 5 and b = 7 as this is addition the answer = 12, however as he defined 4 as his decimal place option his answer should display 12.0000 –  Feb 18 '19 at 19:24
  • @Jaspal Does my edit to the code help it to fit in with what you want the program to do? – Andrew Morton Feb 19 '19 at 13:42
  • I have no idea what your code is supposed to do sorry, i am new to this, i need the value of dp to convert the output of x1 to a decimal to the number of place that is set by dp –  Feb 19 '19 at 17:34
  • @Jaspal Look at the line `Console.WriteLine(String.Format("First Root, (Root1) = {0:F" & decimalPlaces & "}", x1))` and imagine the variable `decimalPlaces` is named `dp`. It does what you're asking. (It is usual to give variables descriptive names.) It is intended to be used in your `Sub QuadraticFunction()` method, I just omitted the rest of the code for clarity. – Andrew Morton Feb 19 '19 at 18:02
  • ok, ive tried it, im just getting the answer but with 2.00 if i input i want 4 dp, i still get the value 2.00 –  Feb 19 '19 at 18:19
  • @Jaspal Did you use your menu item to change the decimal places? I set it to start out at 2 in case the user does not set it to something else. – Andrew Morton Feb 19 '19 at 18:29
  • So it has started working with this however a few problems, it does not tell the user that the values must be between 1 and 5, also am confused with this Option Infer On Option Strict On, when i had this I was getting an error for my console.readline in my menu, where should i place your code as my menu was above this however it is not accepting this now, as the Option Infer On Option Strict Off must be at the top –  Feb 19 '19 at 19:27
  • @Jaspal 1) Oops, I have corrected the display of the error message. 2) Please see [What do Option Strict and Option Explicit do?](https://stackoverflow.com/a/29985039/1115360) - you really should use Option Strict On. 3) You can put your code after the Option statements. Some adjustments may be needed to get the variable types correct - you can use things like [`Convert.ToDouble()`](https://learn.microsoft.com/en-us/dotnet/api/system.convert.todouble?view=netframework-4.7.2) to convert strings entered by the user, such as "2.75" into the number 2.75. – Andrew Morton Feb 19 '19 at 19:46
  • After looking at what you sent me, it seems like Option Explicit means I do not need to declare the Dim before, however as one of the requirement for this code, this is needed by the end user, if I didn't include the Option Strict or the Option Explicit would it still enable the code to work without any error. –  Feb 20 '19 at 10:22
  • @Jaspal I think that Option Explicit is on by default - "On" means that you are required to declare variables to use them. Option Infer is the one that works out the type of a variable from the Dim statement, e.g. the compiler figures that `n` is an integer if you use `Dim n = 1`. It is very useful when using LINQ with anonymous types. It does not stop you from explicitly declaring types. In the code in the question, `a = Console.ReadLine()` is wrong because that is assigning a string to an integer. But it's your code, and if you don't need it to be reliable then there is no problem ;) – Andrew Morton Feb 20 '19 at 10:30
  • Andrew, thank you for your help, I was wondering if it would be possible for me to send you my code and you would be tell me what I need to do to make it more professional and any recommendations you would give me. Thank you –  Feb 22 '19 at 11:40
  • @Jaspal Sorry, I'm not able to help like that at the moment. I can however suggest the [Visual Basic Fundamentals for Absolute Beginners](https://channel9.msdn.com/Series/Visual-Basic-Fundamentals-for-Absolute-Beginners) videos as the ones I watched from an earlier version of the series were clear and gave good advice. – Andrew Morton Feb 22 '19 at 14:47
1

You can use the ":" character to specify the format. You will notice that I have the format as "0." & strDup(). This will output a format of 0.000 if DP is 3 as the StrDup function duplicates the "0" character DP times and appends it to "0."

Module Module1

    Dim DP As Integer  '<---- Notice that it is not declared in a sub().

    Sub Main()

        Dim DecimalPlace As Integer

        Dim blnGoodAnswer As Boolean

        Dim x1 As Double = 3
        Dim x2 As Double = 16

        blnGoodAnswer = False
        Do Until blnGoodAnswer
            Console.WriteLine("Please Enter the Decimial Limit between 1-5:    ")
            Integer.TryParse(Console.ReadLine(), DecimalPlace)
            If (DecimalPlace < 1) Or (DecimalPlace > 5) Then
                Console.WriteLine("Error, Decimial Limit is between 1 and 5, Please Try Again!")

            Else
                DP = DecimalPlace

                blnGoodAnswer = True

                Console.WriteLine("Decimial Limit has been Set Succuesfully to " &
                                  DP & " Decimal Places")

                Console.WriteLine("First Root, (Root1) = " & String.Format("{0:0." &
                                  StrDup(DP, "0") & "}", x1))
                Console.WriteLine("Second Root, (Root2) = " & String.Format("{0:0." &
                                  StrDup(DP, "0") & "}", x2))

            End If
        Loop
    End Sub

End Module

I hope this helps.

IAmNerd2000
  • 761
  • 1
  • 4
  • 12
  • This doesn't work, I've tried it just get the answer 3.00 nothing when I define the decimal value at other numbers than 2 –  Feb 18 '19 at 19:08
  • what are your values of x1? x2? – IAmNerd2000 Feb 18 '19 at 20:11
  • it can be anything, for example the square root of a number, their are two outputs, so x1 and x2 would me my output I have tried this: x1 = (Math.Round(x1, DP)) //// x2 = (Math.Round(x2, DP)) This does not seem to work either –  Feb 18 '19 at 20:14
  • Can you show your code as this should work. so should Andrew Morton's code. – IAmNerd2000 Feb 18 '19 at 20:26
  • This will not compile with Option Strict On which it should be. – Mary Feb 19 '19 at 02:55
  • What is this supposed to mean? `DP = DP` – Mary Feb 19 '19 at 02:56
  • @Mary I copied the OP's code to match it and give an answer as requested. I try not to modify the OP code as they do not always understand multiple modifications. Also, Option Strict On does not allow for implicit conversion which, for this program, does not matter (it is an option). – IAmNerd2000 Feb 19 '19 at 06:13
  • 1
    @IAmNerd2000 I don't think perpetuating bad code is a good practice for what is meant to be not only an answer for the OP but to be a reference for the future. I am not going to argue about Option Strict. That is a given, especially for an inexperienced programmer. – – Mary Feb 19 '19 at 07:22