繁体   English   中英

二进制到十进制的转换

[英]Binary to decimal conversion

我是一名新手程序员,试图编写将输入的二进制数转换为十进制数的程序。 据我所知,数学和代码正确,并且不会返回任何编译错误,但是输出的数字不是正确的十进制数字。 我的代码如下:

  String num;
  double result = 0;
  do {
  Scanner in = new Scanner(System.in);
  System.out.println("Please enter a binary number or enter 'quit' to quit: ");
  num = in.nextLine();
  int l = num.length();
  if (num.indexOf("0")==-1 || num.indexOf("1")==-1 ){
    System.out.println("You did not enter a binary number.");
  }

  for (int i = 0; i < l; i++)
{ 
  result = result + (num.charAt(i) * Math.pow(2, (l - i)));
}
System.out.println("The resulting decimal number is: " +result);
  } while (!num.equals("quit"));


  if (num.equals("quit")){
    System.out.println("You chose to exit the program.");
    return;
  }

您提供的任何帮助将不胜感激。 我试图使我的问题尽可能清楚,但是如果您有任何问题,我会尽力回答。 我没做那么久。 我需要的是让某人仔细检查一下,希望能找到我在某个地方犯的错误,谢谢。

更改

result = result + (num.charAt(i) * Math.pow(2, (l - i)));

result = result + ((num.charAt(i) - '0') * Math.pow(2, i));

或更紧凑

result += (num.charAt(i) - '0') * Math.pow(2, i);

请记住,字符'0'与数字0 (与'1'1 ); num.charAt(i)返回的字符不是整数。


int a = '0';
int b = 0;
System.out.println(Math.pow(2, a));
System.out.println(Math.pow(2, b));

输出:

2.81474976710656E14
1.0

没有很大的不同吗?

函数String.charAt(); 不返回数字0或1,您可以将其与该位相乘,但应返回字符“ id”。 您需要将String / char转换为数字。

String num;
  double result = 0;
  do {
  Scanner in = new Scanner(System.in);
  System.out.println("Please enter a binary number or enter 'quit' to quit: ");
  num = in.nextLine();
  int l = num.length();
  if (num.indexOf("0")==-1 || num.indexOf("1")==-1 ){
    System.out.println("You did not enter a binary number.");
  }

  for (int i = 0; i < l; i++)
{ 
  result = result + (Integer.parseInt(num.substring(i,i+1)) * Math.pow(2, (l - i)));
}
System.out.println("The resulting decimal number is: " +result);
  } while (!num.equals("quit"));


  if (num.equals("quit")){
    System.out.println("You chose to exit the program.");
    return;
  }

顺便说一句:为什么不包含0或1的字符串不是二进制数字? 1111为例。 我认为您最好检查“ 0还是1”

if (num.indexOf("0")==-1 && num.indexOf("1")==-1 ){
    System.out.println("You did not enter a binary number.");
  }

请注意, num.charAt(i)给出位置i处字符的ASCII码。 这不是您想要的值。 在对该值进行任何数学运算之前,需要将每个字符数字转换为一个int

Integer.parseInt(string, base)使用“基本”基数将字符串解析为整数,如果无法将其转换,则会引发异常。

import java.util.Scanner;

public class Convertion {

    public static void main(String[] args) {
        String num;
        Scanner in = new Scanner(System.in);
        System.out.println("Please enter a binary number");
        num = in.nextLine();
        try{
              //this does the conversion
              System.out.println(Integer.parseInt(num, 2));
        } catch (NumberFormatException e){
              System.out.println("Number entered is not binary");
        }  
    }
}

暂无
暂无

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

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