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

Java实现任意进制转十进制求和结果异常问题排查求助

问题排查与修复方案

你代码里存在三个核心错误,按优先级排列如下:

  • 求和逻辑位置错误:total += decimal 放在了字符遍历的循环内部,每处理一个字符就累加一次未完成的中间值,导致总和被错误放大了数倍。正确逻辑是等整个数字的十进制值计算完成后,再一次性累加到总和。
  • 非法条目未过滤:检测到字符值大于等于进制后仅跳出循环,没有标记条目非法,也没有跳过累加步骤,非法条目的半截计算值会被错误计入总和。
  • 整数溢出:用int存储转换结果、总和、幂次,32位int最大仅支持2147483647,稍长的多进制数转换后就会溢出变成负数,这是你得到负总和的直接原因,需要替换为long类型。

修正后完整代码

import java.io.BufferedReader;
import java.io.FileReader;

//Class for converting a number with a base value to decimal from each line in a file
public class anyBaseToDecimal {
    // Main function
    public static void main(String[] args) throws Exception {
        // Declares line as string to store a line in file
        String lines, numString;
        // 进制用int足够,结果、总和、幂次改用long避免溢出
        int base, val;
        long total = 0, decimal, power;
        // Declare a character variable letter to store each character in numString
        char letter;
        // Opens a file in read mode
        FileReader file = new FileReader("BaseConversionInput.txt");
        BufferedReader br = new BufferedReader(file);
        // Gets each line till end of file is reached
        while ((lines = br.readLine()) != null) {
            // 兼容多个空格的分割
            String wordsArray[] = lines.trim().split("\\s+");
            // Sets numString as first word in wordsArray
            numString = wordsArray[0];
            // Convert numString to uppercase
            numString = numString.toUpperCase();
            // Convert second word in array to integer and store it as base value
            base = Integer.parseInt(wordsArray[1]);
            // set decimal as 0 . It is used for storing decimal equivalent of number
            decimal = 0;
            // set power as 1
            power = 1;
            // 标记当前条目是否合法
            boolean isValid = true;
            // Repeat the loop through each character in numString
            for (int i = numString.length() - 1; i >= 0; i--) {
                // Set letter as ith character of numString
                letter = numString.charAt(i);
                // If letter is a digit set value as letter-48. It is equivalent to its integer
                // value
                if (letter >= '0' && letter <= '9') {
                    val = letter - 48;
                } else {
                    // Set val as decimal equivalent of character ie A=10,B=11,C=12 etc
                    val = letter - 'A' + 10;
                }
                // If val is greater than or equal to base print invalid number and goto next
                // line
                if (val >= base) {
                    System.out.println("Not a valid number!");
                    isValid = false;
                    break;
                }
                decimal += power * val;
                power = power * base;
            }
            // 仅合法条目累加总和、输出转换结果
            if (isValid) {
                System.out.println(decimal);
                total += decimal;
            }
        }
        // display total
        System.out.println("total of decimal equivalent of numbers present in given file: " + total);
        // closes the file
        br.close();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 14:09:02