如何让这段C语言代码正常运行?编写用户输入函数遇问题
Fixing Your GPA Calculator Code
Hey there! No worries at all—everyone starts somewhere, and your code has a solid core. Let's break down the issues and get it working properly.
First, let's go over the key problems in your current code:
- Missing return value for
GetIntFromUser: You declared this function to return anint, but there's noreturnstatement inside it. This leads to undefined behavior in C. Since the function's job is to fill the grades array, it doesn't need to return anything—we should change its return type tovoid. - Incorrect function call in
main: You tried to useprintf(GetIntFromUser());, which is wrong.GetIntFromUserneeds thegradesarray as an argument, and it doesn't produce output forprintfto display. You just need to call it directly with the array. - Minor loop clarity: Your loops use
counter <4, which only processes 4 grades. If you intended to use all 5 slots in thegradesarray, you'd want to change that tocounter <5, but we'll stick with your original 4-grade logic for now.
Here's the fixed code with explanations:
#include<stdio.h> // Change return type to void since we don't need to return a value void GetIntFromUser(int grades[5]); void GetIntFromUser(int grades[5]) { int counter = 0; int incre = 1; // If you want 5 grades, change this to counter <5 while(counter < 4) { printf("Please enter GPA %d: ", incre); scanf("%d", &grades[counter]); incre++; counter++; } } int main() { int sum = 0; int grades[5]; int counter = 0; // Correctly call the function and pass the grades array GetIntFromUser(grades); while(counter < 4) { sum += grades[counter]; // Shorthand for sum = sum + grades[counter] counter++; } // Cast sum to float before division to get a decimal result float gpa = (float)sum / counter; printf("The average GPA is %.2f\n", gpa); return 0; }
What we changed:
- Updated
GetIntFromUserto returnvoid: This removes the undefined behavior from missing a return value, since the function's purpose is to modify the input array rather than return data. - Fixed the function call in
main: We now callGetIntFromUser(grades);directly, passing the array so the function can fill it with user input. - Used shorthand for addition:
sum += grades[counter]is just a cleaner way to write the same sum logic you had. - Clarified the division: Casting
sumtofloatensures we get a floating-point average instead of integer division (which would truncate decimals).
If you want to expand this to handle 5 grades instead of 4, just change both counter <4 conditions to counter <5—the rest of the code will adjust automatically!
内容的提问来源于stack exchange,提问作者Kaiser381
相关产品推荐
相关产品推荐

