gpt4 book ai didi

Java十进制到二进制转换错误

转载 作者:行者123 更新时间:2023-12-01 18:39:08 24 4
gpt4 key购买 nike

我现在正在做一个数字系统代码,在我的decimalToBinary上,每当我输入一个十进制数时,无论它是什么十进制数,它总是将其转换为1。代码在这里。

public static void decimalToBinary() {

do {
System.out.println("Enter your decimal number");
numDecimal = input.nextInt();

if (numDecimal < 0) {
System.out.println("Enter a valid number!");
}

} while (numDecimal < 0);

int intNum = Integer.valueOf(numDecimal);

int counter = 0;

binaryVal[counter++] = intNum % 2;
intNum = intNum/2;

for (int i = counter-1; i >= 0; i--) {
System.out.println("Your binary number is " + binaryVal[i]);

}

}

最佳答案

您在进行转换时错过了一个循环。下面是工作代码

public static void decimalToBinary() {
int numDecimal = 0;
Scanner input = new Scanner(System.in);
int[] binaryVal = new int[100];
do {
System.out.println("Enter your decimal number");
numDecimal = input.nextInt();

if (numDecimal < 0) {
System.out.println("Enter a valid number!");
}

} while (numDecimal < 0);

int intNum = Integer.valueOf(numDecimal);

int counter = 0;
while(intNum >0){
binaryVal[counter++] = intNum % 2;
intNum = intNum/2;
}

System.out.println("Your binary number is :");

for (int i = counter-1; i >= 0; i--) {
System.out.print("" + binaryVal[i]);

}

input.close();

}

关于Java十进制到二进制转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59979083/

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