我正在尝试制作一个java程序,用户输入一个十进制数,然后将其转换为二进制数。这是我到目前为止所拥有的,但是 while 循环只循环一次,并且当我输入 8 时只给我 0。我知道二进制中的 8 是 1000 所以我不明白我做错了什么。我需要简单的编码。请帮忙谢谢
import java.util.Scanner;
public class binary
{
public static void main (String [] args)
{
Scanner scan = new Scanner(System.in);
int userNum = 0;
int binary = 0;
double newNum = 0;
int count = 0;
System.out.print("Enter a positive base 10 number: ");
userNum = scan.nextInt();
System.out.println();
for(; (Math.pow(2,count) <= userNum); count++)
{
}
while(!(count == 0))
{
if(userNum/Math.pow(2,count) != 0)
{
binary = userNum/(int)Math.pow(2,count);
System.out.print(binary);
}
userNum %= Math.pow(2,count);
count--;
userNum %= (int)Math.pow(2,count));
}
}
}
最佳答案
你不应该重新发明轮子,使用Integer.toBinaryString(int)
以及类似的东西,
Scanner scan = new Scanner(System.in);
System.out.print("Enter a positive base 10 number: ");
if (scan.hasNextInt()) {
int userNum = scan.nextInt();
System.out.printf("%d decimal is %s binary%n", userNum,
Integer.toBinaryString(userNum));
}
此外,Java 类应该以大写字母开头。所以你的binary
可能应该是Binary
。最后,如果需要从二进制转换为十进制,可以使用 Integer.parseInt(String, 2)
.
关于java - 十进制转二进制java程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25840314/