十进制转换错误

编程入门 行业动态 更新时间:2024-10-18 06:01:20
本文介绍了十进制转换错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在编写一个将八进制数转换为小数的程序。它编译正确和一切,但我的转换代码有一些重大错误。对我来说这似乎是完全合乎逻辑的,但不管怎样,当我运行程序时,转换是错误的(即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.

更多推荐

十进制转换错误

本文发布于:2023-10-24 20:07:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524879.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:错误   十进制

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!