【问题标题】:Binary conversion issues二进制转换问题
【发布时间】: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


【解决方案1】:

我在转换数字例程中看到了一个错误,如果 n 不是 GE 而不是基数,则需要一个 else,在其中打印出 n 是什么。这就是为什么您的所有回答都缺少最后一位数字的原因。

祝你好运。

【讨论】:

  • 谢谢!我有它,我可以让它打印出整个东西,但向后。 'int r = n%base: System.out.print(r);如果 (n>=base){ n=n/base;转换数字(n); }' 但我会尝试你所说的,看看是否有效。谢谢!感谢您的帮助。
  • 所以我发现它只是向后打印所有内容,所以我的问题不在于代码的末尾,而是开始。它只取第二个 n/base 的余数(如果 n=245,那么它将在 n=122 处开始取余数)。
【解决方案2】:

您的问题是基本情况:当 n >= base 时您停止,并且永远不会打印出最后一个数字。相反,继续直到 n == 0;这意味着您已经转换并打印了所有位数字。

【讨论】:

  • 当我将 if 语句更改为 if(n>=0) {} 然后我得到一个堆栈溢出错误?有什么建议吗?
  • @GabbieGrapes 我的建议是不要通过反复试验来编程。
【解决方案3】:

我想通了,伙计们!它可能比它需要的更复杂,但它现在有效。

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

感谢您的帮助。

【讨论】:

    猜你喜欢
    • 2021-01-03
    • 1970-01-01
    • 1970-01-01
    • 2013-05-22
    • 2016-07-10
    • 2020-06-04
    • 2011-09-14
    • 2021-07-29
    • 2019-12-16
    相关资源
    最近更新 更多