You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

我的代码出现floating point exception错误,请求定位问题原因

Floating Point Exception Fix & Code Improvements

Root Cause of Floating Point Exception

Your program crashes with a floating-point exception because global variables are zero-initialized before main() runs. The global quantity starts at 0, so when target = rand() % quantity + 1 executes, you're performing rand() % 0—a division-by-zero operation that triggers the exception.

Key Issues & Fixes

1. Global Variable Mismanagement

  • Global quantity, target, void_numbers, and points are initialized before user input, leading to invalid values (like division by zero).
  • Local variables in main() shadow global ones, causing confusion and uninitialized variable usage (e.g., local quantity is used in rand() % quantity +1 before being assigned).
  • Fix: Eliminate unnecessary global variables. Declare variables in main() or pass them as parameters to functions. Initialize all variables before use.

2. Undefined Variable invalidinput

The loop while(invalidinput) references an undeclared variable, which is a compiler error.

  • Fix: Replace with a boolean flag initialized to true, or restructure the loop to check input validity directly.

3. Broken Void Number Generation

  • The global unique flag isn't reset to true for each new number, so after the first duplicate, no more numbers are added to void_numbers.
  • Generated void numbers aren't checked against target to ensure they're distinct.
  • The duplicate removal loop has incorrect logic (erases elements improperly and fails to replace them with valid numbers).
  • Fix: Use a std::unordered_set to track existing void numbers (automatically handles uniqueness). Reject any number equal to target when generating.

4. Poor Input Handling

After clearing input errors, cin >> discard_value doesn't reliably consume invalid input.

  • Fix: Use cin.ignore(numeric_limits<streamsize>::max(), '\n') to skip the entire line of invalid input.

Corrected Code

#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <ctime>
#include <unordered_set>
#include <limits>

using namespace std;

string check_guess(int guess, const vector<int>& void_numbers, int target, int& guesses, int points) {
    for (int num : void_numbers) {
        if (guess == num) {
            return "You guessed a void number. You lose.";
        }
    }
    if (guesses == 0) {
        return "You ran out of guesses. You lose.";
    }
    if (guess < target) {
        guesses--;
        return "Your guess is lower than the number.";
    } else if (guess > target) {
        guesses--;
        return "Your guess is higher than the number.";
    } else if (guess == target) {
        return "You guessed the number. You win " + to_string(points) + " points.";
    } else {
        return "Invalid input. Please try again.";
    }
}

void generate_void_numbers(vector<int>& void_numbers, int quantity, int target) {
    unordered_set<int> used;
    while (used.size() < quantity) {
        int num = rand() % 20 + 1; // Target is between 1-20 per game rules
        if (num != target && used.find(num) == used.end()) {
            used.insert(num);
        }
    }
    void_numbers.assign(used.begin(), used.end());
}

void get_void_quantity(int& quantity) {
    cout << "How many void numbers would you like to add? (1-19): " << endl;
    while (true) {
        if (cin >> quantity && quantity >=1 && quantity <=19) {
            break;
        } else {
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            cout << "Invalid input. Please try again." << endl;
        }
    }
}

int main() {
    srand(time(0));
    int guesses = 3;
    int quantity;
    int target = rand() %20 +1; // Target is 1-20 per game rules
    vector<int> void_numbers;
    int points;

    cout << "Welcome to the Numbers Game." << endl;
    cout << "1. In this game you have 3 guesses to guess a randomly-generated number between 1 and 20. The game will inform you if your guess is higher or lower than the random number." << endl;
    cout << "2. If you guess the number without running out of guesses, you receive 10 points. If you want more points, you have the option of inputting a quantity of void numbers." << endl;
    cout << "3. Void numbers make you instantly lose the game if you guess one of them, but each additional void number adds 5 additional points to your total score." << endl;
    cout << "4. If you use all your guesses and don't guess the number, you lose the game." << endl;

    get_void_quantity(quantity);
    generate_void_numbers(void_numbers, quantity, target);
    points = 10 + quantity *5;

    // Optional: Print void numbers for testing
    cout << "\nVoid numbers (for testing): ";
    for (int num : void_numbers) {
        cout << num << " ";
    }
    cout << "\nTarget (for testing): " << target << endl;

    // Game loop for guesses
    while (guesses >0) {
        int guess;
        cout << "\nEnter your guess: ";
        if (!(cin >> guess)) {
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            cout << "Invalid input. Please enter an integer." << endl;
            continue;
        }
        string result = check_guess(guess, void_numbers, target, guesses, points);
        cout << result << endl;
        if (result.find("win") != string::npos || result.find("lose") != string::npos) {
            break;
        }
    }

    return 0;
}

Additional Notes

  • The corrected code uses std::unordered_set to ensure void numbers are unique and not equal to the target.
  • Input handling is improved to properly consume invalid input lines.
  • Functions are modularized for better readability and maintainability.
  • The full game loop is added to handle user guesses (missing in your original code).

内容的提问来源于stack exchange,提问作者doroyoki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 15:54:53