我正在处理一个应该接受用户输入的代码,然后将其转换为基数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
答案 0 :(得分:0)
您的问题是基本情况:当n&gt; =基数时停止,并且永远不会打印出最后一位数字。相反,继续前进,直到n == 0;这意味着您已经转换并打印了所有数字。
答案 1 :(得分:0)
我在转换编号例程中看到一个错误,如果n不是GE而不是基数,则需要一个else,在那里打印出n是什么。这就是为什么你的所有回复都缺少最后一位数的原因。
祝你好运。
答案 2 :(得分:0)
我想出来了!它可能比它需要的更复杂,但它现在有效。
private static void convertNumber(int n, int base) {
int m = n;
int j=1;
if (n >= base ||n==0) {
n = n/base;
convertNumber(n, base);
if (j != 1){
int r = (n % base);
System.out.print(r);}
else {
int r = (m % base);
System.out.print(r);
j++;}}
else{
int r = (n % base);
System.out.print(r);}
} //end convertNumber
感谢您的帮助。