我試圖將十進制轉換爲二進制,但一些如何當我轉換128二進制輸出給我11111110,我試圖修復計算,但仍然以相同的輸出結束。將十進制轉換爲二進制(Java)
import java.lang.*;
public class HA7BinaryErr {
public static void main(String[] argv) {
Scanner input = new Scanner(System.in);
int number = 0;
int factorOfTwo = 0;
// get number to convert from user
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 : ");
// convert to binary by successively dividing by larger factors of 2
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
什麼的'factorOfTwo'它出了問題的第一個值? –
如果您要求人們嘗試閱讀,請始終縮進您的代碼。 – khelwood
[將小數轉換爲二進制Java]可能的重複(http://stackoverflow.com/questions/14784630/converting-decimal-to-binary-java) – UserF40