C语言程序函数莫名重复执行求助:整数求平均与负数检测异常
Hey there! Let's break down why your function is repeating unexpectedly and fix those issues step by step.
The Root Causes of the "Repeating Execution" Issue
1. Recursive Calls Aren't Handled Properly
When you call averageOrNegative(sum, counter) recursively (after the user presses 'y'), you don't capture its return value or exit the current function instance. This means after the recursive call finishes, the original function will keep running the remaining code (the test printfs and return statement), creating the illusion of repeated execution.
2. Integer Division Causes Precision Loss
sum/counter uses integer division (since both operands are integers), which truncates decimal values (e.g., 5/2 becomes 2 instead of 2.5). Assigning this to a double won't fix the truncation—it just converts the already truncated integer to a float.
3. Minor: Value Passing Misconception
You mentioned trying to avoid resetting sum and counter by declaring them outside the function, but since you're passing them as parameters (value pass), each function call gets its own copy. Your recursive logic does pass updated values correctly, but the recursive return issue was masking this.
Fixed Code
#include <stdio.h> double averageOrNegative(int sum, int counter); int main(){ int sum = 0, counter = 0; double number = averageOrNegative(sum,counter); printf("\nFinal Result: %f\n", number); // Add to show final output return 0; } double averageOrNegative(int sum, int counter){ int input = 0; double result = 0; char yesORno = ' '; printf("\nPlease input a number \n"); scanf("%d", &input); if(input >= 0){ counter++; sum += input; printf("\ndo you want to input another number, press y for yes\n"); scanf(" %c", &yesORno); if(yesORno == 'y'){ // Fix: Return the recursive call's result directly to exit current instance return averageOrNegative(sum, counter); }else{ // Fix: Cast one operand to double for floating-point division result = (double)sum / counter; } }else{ result = input; } // These test lines now only run for the final function instance printf("\nSum: %d | Counter: %d", sum, counter); printf("\nThis is being run\n"); printf("Current Result: %f\n", result); return result; }
Key Fixes Explained
- Recursive Return Handling: When the user chooses to continue inputting numbers, we use
return averageOrNegative(sum, counter);instead of just calling the function. This passes the recursive result directly back to the parent function and exits the current instance immediately, eliminating the repeated execution. - Floating-Point Division: Casting
sumtodoubleensures the division uses floating-point arithmetic, preserving decimal precision in the average. - Final Result Print: Added a line in
main()to display the final returned value, so you can easily verify the output.
内容的提问来源于stack exchange,提问作者jasongraves

