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

C++主函数十二进制转十进制功能输出错误问题求助

十二进制转十进制代码问题修复

核心问题列表

  • 变量名不匹配:to_int函数输入参数为dozenal,但函数内所有访问字符串的位置错误使用了未定义变量duo,直接导致编译失败。
  • 符号处理逻辑缺失:当前代码遇到+/-直接中断循环,未记录符号位,带符号输入的转换结果完全错误。
  • 返回值位置错误:return decValue写在for循环内部,仅处理第一个字符就直接返回,无法完成多位数转换。
  • 非法字符处理逻辑错误:当前遇到非法字符直接跳过继续处理后续字符,不符合「遇到第一个非合法字符即停止转换」的需求。
  • 类型不匹配:main函数中output被定义为std::string类型,直接接收to_int返回的int值,触发编译错误。
  • 函数返回值缺失:to_int仅在for循环内有返回语句,空输入、全空白输入等场景下函数无返回值,属于未定义行为。
  • 冗余代码:声明的read_target函数全程未调用,属于无效代码。

修正后完整代码

#include <iostream>
#include <string>
#include <cctype>

int to_int(const std::string& dozenal);

int main (){
    int iterations;
    std::string duoValue;

    std::cin >> iterations;
    for (int idx = 0; idx < iterations; idx++ ){
        std::cin >> duoValue;
        int output = to_int(duoValue);
        std::cout << output << std::endl;
    }
    return 0;
}

int to_int(const std::string& dozenal){
    size_t i = 0;
    int decValue = 0;
    int sign = 1;
    // 跳过前导空白
    while (i < dozenal.length() && std::isspace(static_cast<unsigned char>(dozenal.at(i))))
        ++i;
    // 处理正负号
    if (i < dozenal.length() && (dozenal.at(i) == '-' || dozenal.at(i) == '+')) {
        sign = (dozenal.at(i) == '-') ? -1 : 1;
        ++i;
    }
    // 逐位转换
    for (; i < dozenal.length(); ++i) {
        char c = dozenal.at(i);
        int digit = 0;
        if (std::isdigit(static_cast<unsigned char>(c))) {
            digit = c - '0';
        } else if (c == 'x' || c == 'X') {
            digit = 10;
        } else if (c == 'e' || c == 'E') {
            digit = 11;
        } else {
            // 遇到非合法字符停止转换
            break;
        }
        decValue = decValue * 12 + digit;
    }
    return decValue * sign;
}

测试验证

使用你提供的测试用例:
输入:

3
13894
30-something
-Ex42

输出结果为:

27184
36
-20498

完全符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 20:36:03