基本上,我正在尝试编写一个将数字从基数 2 转换为基数 10 的程序。我尝试做的是将本网站上“加倍方法”下列出的过程转换为 for 循环,但由于某种原因,数字我越来越大了。
基本公式是(2 * previousTotal)+(保存用户输入二进制数的ArrayList的currentDigit)=previousTotal。
因此,对于二进制的 1011001,数学将是:
- (0 x 2) + 1 = 1
- (1 x 2) + 0 = 2
- (2 x 2) + 1 = 5
- (5 x 2) + 1 = 11
- (11x 2) + 0 = 22
- (22 x 2) + 0 = 44
- (44 x 2) + 1 = 89
然而,控制台打印出 6185 作为结果。我认为这可能与我使用字符的 ArrayList 有关,但是 charWhole.size() 返回 7,这是用户二进制数中有多少位。只要我做 charsWhole.get(w); 但是,我开始得到大数字,例如 49。我非常感谢一些帮助!
我写出了这个循环,根据我在整个代码中放置的一些打印语句和我的变量 addThis 似乎是问题所在。控制台打印出最终总数为 6185,而以 10 为底的 1011001 实际上是 89。
public static void backto2(){
System.out.println("What base are you coming from?");
Scanner backToB10 = new Scanner(System.in);
int bringMeBack = backToB10.nextInt();
//whole
System.out.println("Please enter the whole number part of your number.");
Scanner eachDigit = new Scanner(System.in);
String theirNumber = eachDigit.nextLine();
String str = theirNumber;
ArrayList<Character> charsWhole = new ArrayList<Character>();
for (char testt : str.toCharArray()) {
charsWhole.add(testt);
}
System.out.println(theirNumber); // User's number
System.out.println(charsWhole); // User's number separated into elements of an ArrayList
System.out.println(charsWhole.size()); // Gets size of arrayList, comes out as 7 which seems fine.
int previousTotal = 0, addThis = 0, q =0;
for( int w = 0; w < charsWhole.size(); w ++) {
addThis = charsWhole.get(w); //current digit of arraylist PROBLEM
q = previousTotal *2;
previousTotal = q + addThis; // previous total gets updated
System.out.println(q);
System.out.println(addThis);
System.out.println(q + " and " + addThis + "equals " + previousTotal);
}
System.out.println(previousTotal);