简体   繁体   English

二进制到十进制程序没有给出正确的答案java

[英]binary to decimal program isn't giving correct answer java

So i have to write a program for homework where it takes a binary number and prints out its the decimal form. 因此,我必须编写一个家庭作业程序,其中需要一个二进制数并打印出其十进制形式。 I've tried and and i just can't really get it. 我已经尝试过了,但是我真的做不到。 Like im printing out what it's doing every time in the loop and it looks like im getting the wrong value when i multiply the inputed data by the 2^i. 就像我打印出循环中每次操作的内容一样,当我将输入的数据乘以2 ^ i时,好像获得了错误的值。 If someone could help, that would be amazing 如果有人可以帮助,那将是惊人的

import java.util.Scanner;

public class Homework {

    public static void main(String[] args) {

        @SuppressWarnings("resource")
        Scanner userinput = new Scanner(System.in);

        System.out.println("Enter a binary number (only 1's or 0's): ");
        String binary_number = userinput.next();

        int value = 0;
        int square_value = 0; 

        for (int i = 0; i < binary_number.length(); i++) {


            char binary_place_holder = binary_number.charAt(i); 
            square_value = (int) Math.pow(2, i);

            if (binary_place_holder == '1') {
                value =  (square_value*binary_place_holder+value);
            }
            System.out.println(binary_place_holder+ "  " + square_value + "  " + value); 

        }
        System.out.print(binary_number + " == " + value);
    }
}

The way you determine the exponent is wrong: The exponent is not i . 确定指数的方法是错误的:指数不是i

You need to realize that you are looking at the string from left to right side so from the highest bit. 您需要意识到,您正在从左到右,从最高位开始查看字符串。 This means the first character's exponent is 2^string_length-1 . 这意味着第一个字符的指数为2^string_length-1 Second character's exponent is 2^string_length-2 and so on. 第二个字符的指数为2^string_length-2 ,依此类推。 Therefore as the index i becomes larger, ie as we are scanning the input left to right, the exponent value becomes smaller. 因此,随着索引i变大,即当我们从左到右扫描输入时,指数值变小。

So the exponent is: 因此,指数为:

int exponent = binary_number.length() - 1 - i;

Note : You can of course do things in reverse and start from the end of the input string and determine the exponent that way, I just wanted to do less changes to your code. 注意 :当然,您可以反向执行操作,并从输入字符串的末尾开始,然后以这种方式确定指数,我只是想对您的代码进行较少的更改。


Also, you should add a check to make sure the input is a valid binary number. 另外,您应该添加检查以确保输入的有效二进制数。 You can write your own function to do it but a simpler solution is to use regex matching: 您可以编写自己的函数来执行此操作,但更简单的解决方案是使用正则表达式匹配:

binary_number.matches("[01]+") 

This will return true if the string binary_number contains only '0' and '1' characters, and false otherwise. 如果字符串binary_number仅包含'0''1'字符,则返回true,否则返回false。


Applying all these changes to your code: 将所有这些更改应用于代码:

public static void main(String[] args) {
    @SuppressWarnings("resource")
    Scanner userinput = new Scanner(System.in);

    System.out.println("Enter a binary number (only 1's or 0's): ");
    String binary_number = userinput.next();

    if(!binary_number.matches("[01]+")) {
        System.err.println("\nPlease enter a valid binary number");
    } else {
        int value = 0;
        for (int i = 0; i < binary_number.length(); i++) {
            if (binary_number.charAt(i) == '1') {
                int exponent = binary_number.length() - 1 - i;
                value += (int) Math.pow(2, exponent);
            } 
        }
        System.out.print(binary_number + " == " + value);
    }
}

这可能被认为是作弊行为,但您可以像

System.out.println(Integer.parseInt(binary_number, 2));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM