程序未返回float值且不同编译器结果不一致的技术问询
Let's walk through the problems in your code and fix them one by one:
1. Why Results Vary Across Compilers: Uninitialized Variable
The biggest issue here is that totalGuess is declared but never initialized in your main function. In C, local variables don't get a default value—they hold whatever "garbage value" was left in that memory location by the system or previous operations.
This is called undefined behavior: different compilers, operating systems, or even runs on the same system can give this variable a different starting value. That's why your total guess count (and eventually the average) is all over the place depending on where you compile/run the code.
The fix is simple: initialize totalGuess to 0 when you declare it:
int i, userInput, compGuess, totalGuess = 0; // Initialize to 0
2. Why Your Program Isn't Returning a Float Value
Your averageGuess function is declared as void, which means it can't return any value at all—let alone a float. Plus, even if you tried to calculate the average inside it, using integer division (like totalGuess / 50) would truncate the result to an integer, losing any decimal precision.
Here's how to fix this:
- Change the function's return type to
floatso it can send back a floating-point average. - Use floating-point division (either cast
totalGuessto float or divide by50.0instead of50) to avoid integer truncation.
Fixed Full Code
#include <stdio.h> #include <stdlib.h> #include <time.h> // Updated function declaration to return float float averageGuess(int totalGuess); int main() { int i, userInput, compGuess, totalGuess = 0; // Initialized totalGuess int loopGuess = 0; srand(time(NULL)); printf("Please enter a number between 0 and 99:\n"); scanf("%d", &userInput); for(i = 0; i < 50; i++) { loopGuess = 0; do { compGuess = (rand() % 100); loopGuess++; } while(compGuess != userInput); totalGuess += loopGuess; } // Capture the float result and print it float average = averageGuess(totalGuess); printf("Average number of guesses: %.2f\n", average); return 0; } // Function implementation that returns a float average float averageGuess(int totalGuess) { // Cast totalGuess to float, or use 50.0 to trigger floating-point division return (float)totalGuess / 50.0; }
Key Notes on the Fixes
- Initialization: By setting
totalGuess = 0, you eliminate undefined behavior and ensure consistent starting values across all compilers. - Floating-Point Division: Using
(float)totalGuessconverts the integer to a float before division, and50.0is a floating-point literal—either of these will prevent integer truncation, giving you a precise decimal average. - Return Type: Changing
averageGuessto returnfloatlets you pass the calculated average back tomainfor printing or further use.
内容的提问来源于stack exchange,提问作者Starch Wars

