我今年16岁,正在尝试学习Java编程。我开始创建此代码,但我不知道它是否正确。你为什么要我把“自然”变成静态?请提出您可以想到的有关代码的任何注释,我会尝试提高我的编程技能,因此,比我了解更多的人的任何注释都是有帮助的。谢谢!
import java.util.Scanner;
public class Prueba {
static int natural;
public Prueba () {
natural = 1;
}
public int Binario(int natural) {
int i = 1, bin = 0;
while(natural>0) {
if (natural % 2 == 0)
natural = natural / 2;
else {
natural = (natural-1)/2;
bin = bin + i;
}
i = i*10;
}
return bin;
}
public static void main(String[] args) {
Prueba a = new Prueba();
Scanner in = new Scanner(System.in);
System.out.println("Natural to binary number converter. Press 0 to stop the program");
while (natural != 0) {
natural = in.nextInt();
System.out.println(a.Binario(natural));
}
}
}
答案 0 :(得分:0)
如果您想返回二进制字符串,可以用这种方法。但是,有几件事需要注意(在评论中有介绍)。
另外,当您将natural
数字表示为二进制数时,我不确定您是指正数还是十进制数。此方法将同时处理两者。但是,十进制负数不会在二进制数中带有负号。它们将以称为Two's Complement的形式显示。在继续学习编程时应该熟悉的东西。
public static String toBinary(int v) {
StringBuilder sb = new StringBuilder();
// since you want to handle negative numbers it's important
// to check for not equal to 0.
while(v != 0) {
// insert the bit at index 0 of stringBuilder.
// The & just masks off the low order bit and ignores
// the others. The result is the same as "v % 2". But
// I prefer bit manipulation when possible
sb.insert(0,v&1);
// this shifts all 32 bits right one bit and inserts a 0
// on the left.
v>>>=1;
}
return sb.toString();
}
在Bit Masking上查看链接以获取更多信息