有人可以为我解释这段代码吗?基本转换代码

时间:2016-02-01 01:38:53

标签: base-conversion

因此,对于家庭作业,我们必须制作一个程序,将一个数字从一个基数转换为另一个基数(即基数为10的110到基数10的6)。我问我的朋友他是怎么做的,因为我遇到了麻烦,他只是把他的代码寄给我,没别的。有人可以解释这段代码的逻辑,这样我就可以制作自己的程序,并真正了解如何解决这个问题。谢谢!

import java.util.*;
public class Base_Converter {
    public static final String value = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    public static void main(String args[]){
    int x, y;
    String num, base10 = "";
    Scanner scan = new Scanner(System.in);

        System.out.println("Enter a number you want to convert.");
        num = scan.nextLine();
        num = num.toUpperCase();
        System.out.println("What base is it in?");
        x = scan.nextInt();
        System.out.println("What base do you want to convert it to?");
        y = scan.nextInt();
        if(x <= 36 && y <= 36 && x > 1 && y > 1){
        base10 = toBase10(num,x);
        num = newBase(base10,y);
        System.out.println(num);
        }
    }
    public static String toBase10(String num, int from){
        long total = 0;
        int counter = num.length();
        char[] stringArray = num.toCharArray();
        for(char w : stringArray){
            counter--;
            total += value.indexOf(w)*Math.pow(from,counter);
        }
        return String.valueOf(total);
    }
    public static String newBase(String num, int to){
        String total = "";
        int current = 0;
        while(Integer.valueOf(num) > 0){
            current = Integer.valueOf(num)%to;
            total = value.charAt(current)+total;
            num = String.valueOf(Integer.valueOf(num)/to);
        }
    return total;
    }
}

1 个答案:

答案 0 :(得分:0)

我认为你不应该关注你朋友的代码所做的事情,而应该关注如何自己完成任务,因为我认为你的问题在于缺乏对你的理解。虽然我会引导您完成基本转换的一些细节,但不要让您高低干燥。

首先,阅读用户输入。看起来您正在使用Java,因此只需使用scanner即可。至少你会想要读取你正在转换的数字,它的基数以及输出的基数。

接下来,我们要转换数字。您可以直接将数字转换为彼此(即将基数2转换为基数8),但这需要比我现在愿意提供的更多智力。相反,我建议首先将用户输入的数字转换为基数10(就像你的朋友那样)。那么我们如何将一些未知基数转换为基数10?

因此,让我们分解一个数字的表示方式:假设我们在十进制数字中有234。这相当于4*10^0 + 3*10^1 + 2*10^24 + 30 + 200 = 234。您可以对任何其他数字使用相同的转换。 I.E.如果数字在基数8中为1763,则基数10中的值将为3*8^0 + 6*8^1 + 7*8^2 + 1*8^33 + 48 + 448 + 512 = 1011 base 10try entering 1763 here for proof。因此要转换为十进制,您只需要查看将你的基数乘以每个单独的数字时间减去它的位数减去1.例如,因为11763中的第四个数字,所以你将它乘以8^(4-1)。因为,你是从用户读取字符串。您需要使用ascii chart将字符串的每个字符转换为整数。

现在从十进制转换为任何东西。而不是乘法,你只需要划分每个值并写下余数! I'll let someone else describe this procedure.

现在只需将这个新值存储为字符串,例如

String output = "";
output += newValue;

在计算机科学中,只是复制别人的代码比有用的更有害。希望这有帮助!