【发布时间】:2017-03-28 18:58:24
【问题描述】:
我正在编写一个应该接受用户输入的代码,然后将其转换为以 2 到 9 为基数的二进制。(对不起,如果这些是错误的术语,对二进制的概念来说是全新的。)我有代码完成,但缺少一些东西。这是用户输入“245”时应该输出的内容
converted to base 2 = 11110101
converted to base 3 = 100002
converted to base 4 = 3311
converted to base 5 = 1440
converted to base 6 = 1045
converted to base 7 = 500
converted to base 8 = 365
converted to base 9 = 302
但是,这是我的输出结果:
converted to base 2 = 1111010
converted to base 3 = 10000
converted to base 4 = 331
converted to base 5 = 144
converted to base 6 = 104
converted to base 7 = 50
converted to base 8 = 36
converted to base 9 = 30
这是我的代码:
import java.util.*;
public class Tester {
public static void main(String args[]) {
//ask user for number
Scanner k = new Scanner(System.in);
System.out.println("Please enter a positive integer.");
int input = k.nextInt();
System.out.println();
//this loop converts the number into each base from 2 to 9
//for each base the loop calls the convertNumber() method to do the conversion
for(int i=2; i<=9; i++) {
System.out.print("converted to base " + i + " = ");
convertNumber(input, i);
System.out.println();}
}
/*
* Recursive method that prints the given number in the given base
* example: if n = 13 and base = 2 (binary) then 1101 should be displayed
*/
private static void convertNumber(int n, int base) {
if (n >= base) {
n = n/base;
convertNumber(n, base);
int r = (n % base);
System.out.print(r);
}
} //end convertNumber
}//ends Tester
【问题讨论】:
-
我认为这是为了家庭作业或其他事情。否则你可以使用
Integer.parseInt()。 -
是的,由于某种原因,我的计算机上的代码总是有问题。我总是出错。我们的一本书的代码有这个,为了让程序运行,我不得不把那个代码拿出来。
标签: java recursion methods binary int