gpt4 book ai didi

java - 十进制转二进制,打印错误答案

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:55:01 25 4
gpt4 key购买 nike

嘿,我想知道是否有人能发现我的代码有问题吗?如果可以的话,请给我解释一下!当我输入 99 时,我得到 1100 011,而它应该是 0110 0011。

import java.util.*;
public class SchoolHomework {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Program that converts decimal to binary!");
int dec;
System.out.println("Please type in a decimal number:");
Scanner input = new Scanner(System.in);
Stack<Integer> todec = new Stack<Integer>();
dec = input.nextInt();
if (dec < 0){
System.out.println("Error: Please enter a positive number!");
System.exit(0);
}
while (dec != 0){
int stackv = dec % 2;
todec.push(stackv);
dec /= 2;

}
System.out.println(dec + " To binary is: ");
int counter = 0;
while (!(todec.isEmpty() )) {
String val = todec.pop().toString();
System.out.print(val);
counter = counter + 1;
if (counter >= 4){
counter = 0;
System.out.print(" ");
}

}
}
}

最佳答案

你写的算法看起来很不错。你离解决方案很近了。最简单的方法是继续将零压入堆栈,直到长度达到 4 的倍数。如果你有什么好意见,请告诉我 ;)

import java.util.*;
public class SchoolHomework {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Program that converts decimal to binary!");
int dec;
System.out.println("Please type in a decimal number:");
Scanner input = new Scanner(System.in);
Stack<Integer> todec = new Stack<Integer>();
dec = input.nextInt();
if (dec < 0){
System.out.println("Error: Please enter a positive number!");
System.exit(0);
}
int size = 0;

while (dec != 0){
int stackv = dec % 2;
todec.push(stackv);
dec /= 2;
size++;
}
if (size % 4 > 0) {
for(int i = 0; i < 4 - (size % 4); i++) {
todec.push(0);
}
}
System.out.println(dec + " To binary is: ");
int counter = 0;
while (!(todec.isEmpty() )) {
String val = todec.pop().toString();
System.out.print(val);
counter = counter + 1;
if (counter >= 4){
counter = 0;
System.out.print(" ");
}

}
}
}

关于java - 十进制转二进制,打印错误答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35308963/

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