如何在FreeBASIC中利用数组实现教师薪资数据的查询打印?
Got it, let's walk through how to finish this up using your arrays to pull and display the teacher data when the user inputs a number. Here's a step-by-step breakdown and complete code example:
Step 1: Initialize Your Arrays with Teacher Data
First, you need to populate your arrays with actual teacher info before letting the user input a number. Since you set Teachers = 2, we'll fill the first two indices (your loop uses 1 To Teachers, so we’ll stick with 1-based indexing here):
Dim Names(10) As String Dim Yos(10) As Integer Dim Sal(10) As Integer Dim Nsal(10) As Integer Dim Rate(10) As Integer Teachers = 2 Teacher_Num = 0 Dim Number As Integer Dim Answer As String ' Populate array data for your 2 teachers Names(1) = "Ms. Eleanor Vance" Yos(1) = 7 Sal(1) = 62000 Rate(1) = 6 ' 6% raise percentage Names(2) = "Mr. Jack Torrance" Yos(2) = 12 Sal(2) = 78000 Rate(2) = 4 ' 4% raise percentage ' Pre-calculate new salaries for all teachers For Count = 1 To Teachers Nsal(Count) = Sal(Count) * (1 + Rate(Count) / 100) Next Count
Step 2: Add User Input Handling & Data Display
Next, we’ll add a loop to let users input a teacher number, validate the input, and print the requested details. We’ll also include an option to quit the program:
PRINT "Congrats! 10 of you have been chosen to receive a raise in your salary :D. Please follow instructions below :)." PRINT Do PRINT "Enter a teacher number (1 to "; Teachers; ") to view their salary details, or type 'Q' to quit:" INPUT Answer ' Check if user wants to exit If UCase(Answer) = "Q" Then PRINT "Goodbye!" Exit Do End If ' Convert input to a number and validate it's within range Number = Val(Answer) If Number >= 1 And Number <= Teachers Then ' Pull data from arrays and display it PRINT vbCrLf & "Teacher Details:" PRINT "Name: " & Names(Number) PRINT "Current Salary: $" & Format(Sal(Number), "#,##0") PRINT "New Salary (After Raise): $" & Format(Nsal(Number), "#,##0") PRINT vbCrLf Else PRINT "Invalid input! Please enter a number between 1 and "; Teachers; "." PRINT vbCrLf End If Loop
Quick Tips to Keep in Mind
- Index Safety: By validating the user’s input against
1 To Teachers, you avoid trying to access array positions that aren’t populated (which would cause errors). - Readability: Using
Format()adds commas to salary numbers, making them easier to read for users. - Reusability: If you later add more teachers, just update the
Teachersvariable and populate the next array indices—no need to rewrite the input/display logic.
内容的提问来源于stack exchange,提问作者Alysia56
相关产品推荐
相关产品推荐

