简体   繁体   English

我的方法有什么问题?

[英]What is wrong with my method?

I just wanted to create a method which can convert a number from binary system(base2) to decimal system(base10). 我只是想创建一个可以将数字从二进制系统(base2)转换为十进制系统(base10)的方法。 But I come up with some problems. 但是我提出了一些问题。 I don't know how to correct it. 我不知道该如何纠正。 Here is my method 这是我的方法

public static int toDecimal (String base2) 
   {
     int sum=0;

     for ( int k=base2.length(); int i=0; k>0, i<=base2.length()-1; k--, i++)
     {
       char symbol = base2.charAt(k);
       sum= sum+ symbol*i;
     }
     return sum;
   }

PS: I could not be able to convert a character to integer type (sum+ symbol*i;) . PS:我无法将字符转换为整数类型(sum + symbol * i;) If possible, could you also give some advice about it. 如果可能的话,您也可以提出一些建议吗?

Actually your code is not working because of incorrect for loop syntax - you can use ; 实际上,由于不正确的for循环语法,您的代码无法正常工作-您可以使用; symbol only two times inside the parentheses. 符号在括号内仅两次。 Also sum = sum + symbol * i; sum = sum + symbol * i; is not right coversion formula. 不是正确的覆盖公式。

It seems that this code resolves your problem 看来这段程式码可以解决您的问题

public static int toDecimal(String base2) {
    int sum=0;
    int i = 0;
    for (int k = base2.length() - 1; k >= 0; k--) {
        sum += Integer.parseInt(String.valueOf(base2.charAt(k))) << i;
        i++;
    }
    return sum;
}

I hope that this helps you! 希望对您有帮助!

just some minor changes to your for loop will get the code working 只需对for循环进行一些细微更改,即可使代码正常工作

public static int toDecimal(String base2) {
    int sum = 0;    
    for (int k = base2.length() - 1, i = 0; k>=0; k--, i++) {
        int symbol = (int)base2.charAt(k)-48;//0 is 48; 1 is 49 in ASCII
        sum = (int) (sum + (int) symbol * Math.pow(2, i));
    }
    return sum;
}

here you go 干得好

In you for loop you initialize 2 variables. 在for循环中,您将初始化2个变量。 Between them you have a ; 他们之间有一个; (semicolon) but there should be a , (comma). (分号),但应有一个(逗号)。

To eliminate the need for the parseInt call, and to start from the beginning of the string, you can use 为了消除对parseInt调用的需要,并从字符串的开头开始,可以使用

   public static int toDecimal( String str) {
      int val = 0;
      for (int i = 0; i < str.length(); i++) {
         val = (val<<1) + ((str.charAt( i ) == '0') ? 0 : 1);
      }
      return val;
   }

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

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