/* This program converts decimal to binary */
import javax.swing.JOptionPane;
public class BinaryLoop {
public static void main(String []args) {
String askForDecimal = JOptionPane.showInputDialog("Enter the decimal number you would like to convert?");
int decimalNumber = Integer.parseInt(askForDecimal);
int remainder = 0;
for (int i = 1; decimalNumber > 0; i++) {
decimalNumber /= 2;
remainder = decimalNumber % 2;
System.out.print(remainder);
}
}
}
例如我輸入15,但它返回1110應該是1111. p.s.這個結果將從右到左讀取。如何使用for循環將小數轉換爲二進制?
這所學校是否工作?你必須使用for循環嗎? – slugmandrew
我的老師不讓我! – TheJuggler
@slugmandrew是的。是的,我必須! – TheJuggler