如何用C语言printf输出含学生、课程及最高分的完整结果?
Solution: Display Highest Grade with Student and Course Details
Hey there! I get what you're aiming for—instead of just showing the highest number, you want to add context by including which student got it, which course it was in, and the mark itself. Let's fix that up.
The main gap here is tracking not just the maximum mark, but also which student and course that mark belongs to. Here's a complete, modified version of your code that implements the exact output format you want:
#include <stdio.h> int main() { // Note: void main() is non-standard; int main() is recommended const int STUDENTS = 3; // Switched to int for flexibility with larger datasets const int COURSES = 3; char students[][15] = { "James", "Keith", "Jonathan" }; char courses[][15] = { "Math", "Science", "English" }; // Added course names array int marks[STUDENTS][COURSES] = { // Sample grade data (replace with your actual values) {85, 92, 78}, {90, 88, 95}, {76, 89, 82} }; // Initialize variables to track the highest mark and its associated details int highest_mark = marks[0][0]; int top_student_idx = 0; int top_course_idx = 0; // Loop through every student's every course to find the highest grade for (int i = 0; i < STUDENTS; i++) { for (int j = 0; j < COURSES; j++) { if (marks[i][j] > highest_mark) { highest_mark = marks[i][j]; top_student_idx = i; top_course_idx = j; } } } // Print the result in your desired format printf("Highest was %s in %s with %d\n", students[top_student_idx], courses[top_course_idx], highest_mark); return 0; // Required for standard int main() }
Key Changes Breakdown:
- Added Courses Array: I included a
coursesarray to store course names, matching the structure of yourstudentsarray. - Tracking Indices: Instead of only storing the highest mark, we keep track of the indices (
top_student_idxandtop_course_idx) where this mark lives. This lets us look up the corresponding names in our arrays later. - Nested Loop Logic: The nested loops check every student's grade in every course. Whenever we find a grade higher than the current maximum, we update our tracking variables to reflect this new top grade.
- Formatted Output: The
printfstatement uses the stored indices to pull the correct student and course names, then prints everything exactly as you requested:Highest was [student name] in [course] with [mark]. - Standard Main Function: I adjusted
void main()toint main()and addedreturn 0;sincevoid main()isn't standard C and can cause issues in some compilers.
If you run this code with the sample data, it will output:
Highest was Keith in English with 95
You can swap out the students, courses, and marks arrays with your actual data easily.
内容的提问来源于stack exchange,提问作者Dante
相关产品推荐
相关产品推荐

