10位以内二进制数字转十进制计算器(Printing the Decimal Equivalent of a Binary Number)
2016-06-17 19:20
627 查看
挺有成就感的一个小程序,二进制转十进制。
代码如下:
运行结果:
请输入要转换的二进制数字:1100001110
二进制数1100001110对应的十进制数为: 782
请输入要转换的二进制数字:10011110
二进制数10011110对应的十进制数为: 158
代码如下:
//JHTP Exercise 4.31: Printing the Decimal Equivalent of a Binary Number //by pandenghuang@163.com /*(Printing the Decimal Equivalent of a Binary Number) Write an application that inputs an *integer containing only 0s and 1s (i.e., a binary integer) and prints its decimal equivalent. [Hint: Use *the remainder and division operators to pick off the binary number’s digits one at a time, from right *to left. In the decimal number system, the rightmost digit has a positional value of 1 and the next *digit to the left a positional value of 10, then 100, then 1000, and so on. The decimal number 234 *can be interpreted as 4 * 1 + 3 * 10 + 2 * 100. In the binary number system, the rightmost digit has *a positional value of 1, the next digit to the left a positional value of 2, then 4, then 8, and so on. *The decimal equivalent of binary 1101 is 1 * 1 + 0 * 2 + 1 * 4 + 1 * 8, or 1 + 0 + 4 + 8 or, 13.]*/ import java.util.Scanner; import java.math.*; public class Binary2Decimal { public static void main(String[] args) { int binary=0; int decimal=0; int len=0; int[] binaryDigit=new int[10]; int counter=0; int tempBinary=0; Scanner input=new Scanner(System.in); System.out.print("请输入要转换的二进制数字:"); binary=input.nextInt(); tempBinary=binary; //1011 len=String.valueOf(tempBinary).length(); while (counter<len){ binaryDigit[counter]=(int)(tempBinary%10); tempBinary/=10; counter++; } counter=0; //decimal=1*1+1*2+0*2*2+1*2*2*2=11 while (counter<len) { decimal+=binaryDigit[counter]*(int)Math.pow(2, counter); counter++; } System.out.printf("二进制数%d对应的十进制数为: %d",binary,decimal); } }
运行结果:
请输入要转换的二进制数字:1100001110
二进制数1100001110对应的十进制数为: 782
请输入要转换的二进制数字:10011110
二进制数10011110对应的十进制数为: 158
相关文章推荐
- UE4(二)学习之路之Matinee制作屏幕淡入淡出效果
- Android学习之 图解调用invalidate()和requestLayout()的过程
- UIAutomator remote debug方法
- easyui datagrid
- UICollectionView基础
- iOS开发UI篇—控制器的View的创建
- ORA-22922 :nonexistent LOB value解决方案
- PHP 继承,组合,单模式,GUID,等混合实例
- easyui datagrid editor在编辑状态下更新列值并不结束编辑。
- UiAutomator和Espresso比较
- 自定义锁超时
- js遍历json的key和value
- Message,Handler,MessageQueue,Looper之间的关系
- minSdkVersion、argetSdkVersion、maxSdkVersion、build target、android系统版本、API Level合理设置各个值的意义
- NYOJ 1100 WAJUEJI which home strong! (BFS)
- iOS开发UI篇—Quartz2D使用(图形上下文栈)
- 关于build.gradle文件操作
- android Gui系统之SurfaceFlinger(3)
- ModernUI + MVVM 加载页面
- Building Crosswalk For Windows