gpt4 book ai didi

java - 二进制到十进制的程序在 Java 代码中给出错误

转载 作者:行者123 更新时间:2023-11-29 07:05:05 25 4
gpt4 key购买 nike

我编写了一个程序将数字从二进制转换为十进制,如果输入是 0011,它会给出错误的输出。对于 0011,答案应该是 3,但它给出的是 9,否则它对于其他输入是正确的。

代码:

public class BinaryToDecimal {
static int testcase1=1001;
public static void main(String[] args) {
BinaryToDecimal test = new BinaryToDecimal();
int result = test.convertBinaryToDecimal(testcase1);
System.out.println(result);
}
//write your code here
public int convertBinaryToDecimal(int binary) {
int powerOfTwo=1,decimal=0;
while(binary>0)
{
decimal+=(binary%10)*powerOfTwo;
binary/=10;
powerOfTwo*=2;
}
return decimal;
}
}

最佳答案

0 开头的整数文字被认为是八进制,即。以 8 为基数。

0011 

(0 * 8^3) + (0 * 8^2) + (1 * 8^1) + (1 * 8^0)

等于 9。

0111 

会是

(0 * 8^3) + (1 * 8^2) + (1 * 8^1) + (1 * 8^0)

等于 73。

您正在寻找 0b0011,它是二进制数的整数文字表示。

关于java - 二进制到十进制的程序在 Java 代码中给出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20697779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com