VB程序无法正确输出输入数值的最大最小值问题求助
Hey there! Let's dig into why your Maxno and Minno are always outputting 0. Based on the code snippet you shared and common mistakes in student score tracking programs, here are the most likely issues and how to fix them:
If you initialized Maxno and Minno to 0 right off the bat, that's probably the problem. For example:
- If all your students' scores are positive,
Minnowill never update because 0 is smaller than any positive score. - If all scores are negative,
Maxnowill stay 0 for the opposite reason.
Fix: Use the first valid score you input to initialize both variables, instead of a fixed 0. Here's how that might look:
' First, get the first valid score Dim currentScore As Integer Do Console.WriteLine(MSG_ENTRYDATA) ' Use TryParse to safely handle invalid input (more on this later) While Not Integer.TryParse(Console.ReadLine(), currentScore) Or currentScore < 0 Or currentScore > 100 Console.WriteLine(MSG_ERROR) Console.WriteLine(MSG_ENTRYDATA) End While Loop Until currentScore >= 0 And currentScore <= 100 ' Now set Maxno and Minno to this first valid score Dim Maxno As Integer = currentScore Dim Minno As Integer = currentScore
If you're not checking each new score against Maxno and Minno as you input them, those variables will never change from their initial values. You need explicit checks inside your input loop.
Fix: Add these checks every time you get a new valid score:
' Inside your loop for additional students If currentScore > Maxno Then Maxno = currentScore End If If currentScore < Minno Then Minno = currentScore End If
If you defined Maxno and Minno inside your input loop, they'll be reinitialized to 0 every time the loop runs. That means their values never persist between iterations.
Fix: Make sure Maxno and Minno are declared outside of any loops that process scores. That way, their values are retained and updated as you input each student's score.
If your code isn't properly validating or converting user input, you might be skipping over valid scores entirely, leaving Maxno and Minno stuck at their initial values. Using Integer.TryParse instead of Integer.Parse is safer—it prevents crashes from non-numeric input and lets you validate the score range at the same time.
Example of Safe Input Handling:
Dim input As String Dim currentScore As Integer Console.WriteLine(MSG_ENTRYDATA) input = Console.ReadLine() ' Keep asking until we get a valid score While Not Integer.TryParse(input, currentScore) Or currentScore < 0 Or currentScore > 100 Console.WriteLine(MSG_ERROR) Console.WriteLine(MSG_ENTRYDATA) input = Console.ReadLine() End While
If you still run into issues, feel free to share your full code—sometimes a small oversight in loop structure or variable assignment is easy to miss!
内容的提问来源于stack exchange,提问作者Dylan Cheng

