首页 > 编程知识 正文

整数十进制转换二进制计算题,十进制变为二进制的计算器

时间:2023-05-04 15:46:52 阅读:285061 作者:3439

挺有成就感的一个小程序,二进制转十进制。


代码如下:

//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;//1011len=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=11while (counter<len){decimal+=binaryDigit[counter]*(int)Math.pow(2, counter);counter++;}System.out.printf("二进制数%d对应的十进制数为: %d",binary,decimal);}}


运行结果:

请输入要转换的二进制数字:1100001110
二进制数1100001110对应的十进制数为: 782

请输入要转换的二进制数字:10011110
二进制数10011110对应的十进制数为: 158





版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。