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

C++几何计算器程序:循环、选择逻辑及密码验证问题排查

几何形状计算器程序问题修复

问题梳理

  • 密码验证模块允许4次错误尝试,不符合3次限制要求
  • 形状选择与计算逻辑异常,无法完成正方体(A)的体积/表面积计算
  • 缺少计算完成后询问用户是否继续的功能

修复方案与完整代码

#include <iostream>
#include <math.h>
#include <limits>

using namespace std;

int main() {
    char code, continue_opt;
    int option, s, l, w, r, h;
    const float pi = 3.14;
    float total = 0;
    string password, username;
    int attempts_left = 3;

    // 密码验证模块:修复尝试次数逻辑
    while (attempts_left > 0) {
        cout << "Enter password: ";
        getline(cin, password);
        cout << "Enter username: ";
        getline(cin, username);

        if (password == "abc" && username == "abc") {
            cout << "Access granted.\n";
            break;
        }

        attempts_left--;
        if (attempts_left > 0) {
            cout << "Invalid password or username. You have " << attempts_left << " attempts left.\n";
        } else {
            cout << "Invalid password or username. No attempts left, exiting.\n";
            return 0;
        }
    }

    // 主计算循环:支持重复计算
    do {
        // 形状选择:修复循环条件逻辑
        while (true) {
            cout << "Enter code (A-G): ";
            cin >> code;
            code = toupper(code); // 兼容小写输入
            if (code >= 'A' && code <= 'G') {
                break;
            }
            cout << "Invalid code, please enter A-G.\n";
        }

        // 正方体(A)计算逻辑:修复未初始化option的问题
        if (code == 'A') {
            // 让用户选择计算类型
            while (true) {
                cout << "Choose option (1: 体积, 2: 表面积): ";
                cin >> option;
                if (option == 1 || option == 2) {
                    break;
                }
                cout << "Invalid option, please enter 1 or 2.\n";
            }

            cout << "Enter edge length: ";
            cin >> s;
            if (option == 1) {
                total = static_cast<float>(s) * s * s;
                cout << "answer = " << total << "\n";
            } else {
                total = 6 * static_cast<float>(s) * s;
                cout << "answer = " << total << "\n";
            }
        }

        // 此处可扩展B-G其他形状的计算逻辑

        // 询问是否继续
        cout << "是否继续使用程序?(Y/N): ";
        cin >> continue_opt;
        continue_opt = toupper(continue_opt);
        // 清除输入缓冲区,避免后续getline读取异常
        cin.ignore(numeric_limits<streamsize>::max(), '\n');

    } while (continue_opt == 'Y');

    cout << "程序已退出.\n";
    return 0;
}

修复说明

  1. 密码验证修复:将输入逻辑整合到循环内,每次验证失败后递减尝试次数,次数耗尽直接退出,确保最多3次错误尝试。
  2. 形状计算逻辑修复:
    • 形状选择循环改为判断输入是否在A-G范围内,解决原逻辑永远为真的死循环问题
    • 补充用户选择计算类型的交互步骤,修复option未初始化导致的逻辑异常
  3. 继续功能实现:用do-while循环包裹完整计算流程,每次计算完成后询问用户是否继续,输入Y则重新启动计算流程,输入N则退出程序。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 23:50:15