2012-10-10 7 views
0

나는 입력 한 이진수를 10 진수로 변환하는 프로그램을 작성하는 초보 프로그래머입니다. 내가 말할 수있는 한, 수학과 코드는 옳으며 컴파일 오류는 반환되지 않지만 출력되는 숫자는 올바른 십진수가 아닙니다. 당신이 줄 수2 진수에서 10 진수로 변환

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; 
    } 

어떤 도움이 많이 주시면 감사하겠습니다 다음과 같이 내 코드입니다. 나는 가능한 한 명확한 질문을하려고 노력했으나 질문이 있으면 최선을 다해 답변하려고 노력할 것입니다. 나는 오랫동안 그렇게 해왔다. 내가 필요로하는 것은 누군가가 그것을 살펴보고 내가 어딘가에서 만든 오류를 발견 할 수 있기를 바랍니다.

+1

, 당신이 실제로 문자를 "변환"하는 좋은 생각이다 2. – dnault

답변

2

변경

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'이 번호같은 일이 아니라는 것을 기억하십시오('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

큰 차이가 아니다?

+1

의 기수로 Long.parseLong (String를, INT 기수를) 사용할 수있는 '0' 자리에 ... –

1

함수 String.charAt();은 숫자 0 또는 1을 반환하지 않으며이 비트에는 문자 "id"가 곱할 수 있습니다. 문자열/문자를 숫자로 변환해야합니다.

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을 생각해보십시오. 난 당신이 더 나은 num.charAt(i) 위치 i에있는 문자의 ASCII 코드를 준다 "도 0이나 1"

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

참고를 확인한다고 생각합니다. 이것은 당신이 원하는 가치가 아닙니다. 값으로 계산하기 전에 각 문자 숫자를 int으로 변환해야합니다.

0

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"); 
     } 
    } 
} 
관련 문제