[英]Converting user input from binary to decimal using Modulus Operator in Java
我很难弄清楚编程1课的家庭作业的答案。 该分配提示用户输入二进制(最多4位),并将其转换为等效的十进制数。 不允许使用循环,条件语句,ParseInt以及除模运算符和其他数学运算符以外的任何内容。
我在数学方面遇到了麻烦,我想一旦我了解了如何使用模运算符来回答这个问题,我便可以为其编写代码。
我已经搜索过,但是找不到任何能够帮助您的东西。
您应该获取每个位置的数字值,并使用2的幂乘以它们,以获取原始数字。
double num = 1110;
double ones = Math.floor(num % 10);
double tens = Math.floor(num/10 % 10);
double hundreds = Math.floor(num/100 % 10);
double thousands = Math.floor(num %10000 /1000);
double tenThousands = Math.floor(num / 10000 % 10);
double original = (ones * 1) +
(tens * 2) +
(hundreds * 4) +
(thousands * 8);
System.out.println(num);
System.out.println("ones: " +ones);
System.out.println("tens: " +tens);
System.out.println("hundreds: " +hundreds);
System.out.println("thousands: " + thousands);
System.out.println("original number : " + original);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.