有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java十进制到二进制,打印错误答案

嘿,我想知道是否有人能发现我的代码有问题?如果你能解释给我听好吗!当我输入99时,我得到1100 011,而它应该是0110 0011

import java.util.*;
public class SchoolHomework {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    System.out.println("Program that converts decimal to binary!");
    int dec;
    System.out.println("Please type in a decimal number:");
    Scanner input = new Scanner(System.in);
    Stack<Integer> todec = new Stack<Integer>();
    dec = input.nextInt();
    if (dec < 0){
        System.out.println("Error: Please enter a positive number!");
        System.exit(0);
    }
    while (dec != 0){
        int stackv = dec % 2;
        todec.push(stackv);
        dec /= 2;

    }
    System.out.println(dec + " To binary is: ");
    int counter = 0;
    while (!(todec.isEmpty() )) {
        String val = todec.pop().toString();
        System.out.print(val);
        counter = counter + 1;
        if (counter >= 4){
            counter = 0;
            System.out.print(" ");
        }

    }
}
}

共 (0) 个答案