您好,我有一个程序可以成功地将十进制转换为二进制。但是,最后代码将 0 除以 0 会导致最后出现错误消息。这是代码。
import java.lang.*;
import java.util.*;
public class BinaryConverter {
public static void main (String[] argv) {
Scanner input = new Scanner (System.in);
int number = 0;
int factorOfTwo = 0;
do {
System.out.println("Enter the number to convert (0-255): ");
number = input.nextInt();
} while (number< 0 || number > 255);
System.out.println("The number " + number + " converted to binary is : ");
for (factorOfTwo = 1; factorOfTwo <= 128; factorOfTwo*=2) {
if (number / factorOfTwo >= 1){
System.out.print("1");
number -= factorOfTwo;
}
else System.out.print ("0");
}
} // end of main
}// end of class