簡體   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