我正在编写一个将八进制数转换为小数的程序。它编译正确和一切,但我的转换代码有一些重大错误。对我来说这似乎是完全合乎逻辑的,但不管怎样,当我运行程序时,转换是错误的(即1转换为36)有人可以指出出错的地方吗?
I am writing a program that will convert octal numbers to decimals. It compiles right and everything but there is something majorily wrong with my conversion code. It seems perfectly logic to me, however somehow when I run the program the conversions are wrong (i.e. 1 is converted to 36) can someone point out what is going wrong?
public static int convert(int octal) { int d1=0,d2=0,d3=0,d4=0,d5=0,d6=0,d7=0,d8=0; if(octal >=9999999){ d8 = (octal-(octal%10000000));} if(octal >=999999){ d7 = (octal-(octal%1000000));} if(octal >=99999){ d6 = (octal-(octal%100000));} if(octal >=9999){ d5 = (octal-(octal%10000));} if(octal >= 999){ d4 = (octal-(octal%1000));} if(octal >= 99){ d3 = (octal-(octal%100));} if(octal >= 9){ d2 = (octal-(octal%10));} if(octal >= 0){ d1 = (octal-(octal%1));} octal = (d8 * 8^7) + (d7 * 8^6) + (d6 * 8^5) + (d5 * 8^4) + (d4 * 8^3) + (d3 * 8^2) + (d2 * 8^1) + (d1 * 8^0); return octal; }这只是我的转换方法,我的主要方法是什么收集 int八进制;
this is just my convert method, my main method is what collects the int octal;
推荐答案这是问题所在:
8^7^ operator 不会按照您的想法执行操作。它做二进制XOR ...
The ^ operator doesn't do what you think it does. It does binary XOR...
但是,我会说整个设计都是明显可疑的。 int 值不是in八进制或任何其他基数 - 它只是一个整数。数字10是数字10,无论是十进制的10,十六进制的A还是八进制的12。如果你有一个你想要解析为八进制数字的字符序列,那么该方法的输入应该是 String ,而不是 int 。
However, I'd say that the whole design is distinctly suspect. An int value isn't "in" octal or any other base - it's just an integer. The number ten is the number ten, whether that's exressed as "10" in decimal, "A" in hex or "12" in octal. If you've got a sequence of characters which you want to parse as octal digits, the input to the method should be a String, not an int.
更多推荐
十进制转换错误
发布评论