简体   繁体   English

Math.pow()无法正常工作?

[英]Math.pow() not working?

this is the code i made, can someone explain me why the output stays 0.0? 这是我编写的代码,有人可以解释一下为什么输出保持为0.0吗?

(I was trying to make a program that converts binary to decimal, and i know that this can be easily accomplished in java in other ways) (我试图制作一个将二进制转换为十进制的程序,并且我知道这可以通过其他方式轻松地在Java中完成)

    package main;

    import java.util.Scanner;

    public class Class1 {

        public static void main(String[] args)
        {
            Scanner scanner = new Scanner(System.in);
            String input = scanner.nextLine();
            int length = input.length();
            double output=0.0;
            String reverse = new StringBuffer(input).reverse().toString();

            for (int i=0; i==length; i+=1){
                switch(reverse.charAt(i)){
                case '1': output = (output + (Math.pow(2, i)));break;
                case '0': break;
                }
            }
            System.out.println(output);
        }
    }

Unless length == 0 , that for loop never executes. 除非length == 0 ,否则for循环永远不会执行。

You might well mean something like: 您可能会说:

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

Also, there is no need to use Math.pow(2, i) - you can use 1 << i and keep it all as an integer. 另外,也不需要使用Math.pow(2, i) -您可以使用1 << i并将其全部保留为整数。

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

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