1.這是我的代碼轉換二進制到十進制,但它不工作。由於某些原因,c值重複。爲什麼c值在給定的代碼中重複?
/**
* Created by Ranjan Yadav on 11.10.2016.
*/
public class BinaryToDecimal {
public static void main(String[] args) {
java.util.Scanner read = new java.util.Scanner(System.in);
System.out.println("Enter a binary number: ");
int binary = read.nextInt();
int total = 0;
int n = 1;
int c = 0;
int number = 0;
while (binary != 0) {
c = binary % ((int) Math.pow(10, n));
binary = binary/10;
number = c * (int)(Math.pow(2, (n - 1)));
total += number;
++n;
}
System.out.printf("The decimal of the binary is %d", total);
}
}
說我輸入1110111.第一次,'1110111%10'爲1,'binary'設置爲111011。第二次,什麼是'111011%100'? – ajb
謝謝c應該只有10次被調度。 –
在IDE調試器中遍歷代碼並檢查每個步驟的中間值。這應該很快顯示你的問題,你會學到一些東西。 –