我制作了一个java控制台程序,它打印输入的二进制值的十进制值。现在,我的程序存在问题
例如输出: 输入input = 10011101,然后二进制值为3534200而不是157
在浏览互联网以获取将二进制值转换为十进制的公式后,这是我制作此程序时的参考。
1 * 2 ^ 7 + 0 * 2 ^ 6 + 0 * 2 ^ 5 + 1 * 2 ^ 4 + 1 * 2 ^ 3 + 1 * 2 ^ 2 + 0 * 2 ^ 1 + 1 * 2 ^ 0 = 157。
我尝试使用长版本制作这个程序,使用for循环...我觉得这是一个愚蠢的挑战?哈哈!
这里是代码(带评论!):
byte binary[] = new byte[127]; //declared a byte array for input value
int power = 2, formula = 0; //declared the power and the formula as int
System.out.print("Enter Binary: "); //prints "Enter binary:"
System.in.read(binary); //inserts the input in the binary array
Integer bin = Integer.parseInt(new String(binary).trim()); //converts the input value to int for another conversion
String b = Integer.toString(bin); //converts the int bin to string
Integer num = Integer.parseInt(new String(b.substring(b.length() - 1).trim()));
//num variable gets the value of last string (should be anyway)
System.out.println("The Decimal Value of " + bin + " is ");
for(int i = b.length(); i > 0; i--){
for(int a = i; a > 0; a--){ //the condition
power = power*2; //as the loop goes, if 2^3 then it should be 8
}
formula = formula + (num * (power)); //as the given formula above, this is what I did
System.out.println("power: " + power);//if you want reference, I left it here
System.out.println("formula: " +formula);
System.out.println("num: " + num);
num = Integer.parseInt(new String(b.substring(i - 1).trim())); //uhm dunno how to describe this, but you'll see
power = 2;
}
System.out.print(formula);
} }
自从我开始使用java以来,这是我所知道的唯一事情。 (请参阅自第4章以来的最后一个问题)请帮助:(
答案 0 :(得分:1)
你有很多问题:
1)Integer.parseInt(new String(binary).trim())
不符合你的想法。因此,你的数字是错误的。
2)你计算错误的力量。
3)一般建议,用一些空行将代码分成有意义的小块。它的眼睛会更容易。
固定程序应如下所示:
public static void main(String[] args) throws IOException {
byte binary[] = new byte[127]; //declared a byte array for input value
int power = 2, formula = 0; //declared the power and the formula as int
System.out.print("Enter Binary: "); //prints "Enter binary:"
System.in.read(binary); //inserts the input in the binary array
Integer bin = Integer.parseInt(new String(binary).trim()); //converts the input value to int for another conversion
String b = Integer.toString(bin); //converts the int bin to string
Integer num; //num variable gets the value of last string (should be anyway)
System.out.println("The Decimal Value of " + bin + " is ");
for(int i = b.length(); i > 0; i--){
power = 1;
num = Integer.parseInt(Character.toString(b.charAt(i-1)));
for(int a = i; a < b.length(); a++){ //the condition
power = power*2; //as the loop goes, if 2^3 then it should be 8
}
formula = formula + (num * (power)); //as the given formula above, this is what I did
System.out.println("power: " + power);//if you want reference, I left it here
System.out.println("formula: " +formula);
System.out.println("num: " + num);
}
System.out.print(formula);
}