简体   繁体   English

使用Java中的Modulus运算符将用户输入从二进制转换为十进制

[英]Converting user input from binary to decimal using Modulus Operator in Java

I am having a hard time figuring out the answer to a homework assignment for Programming 1 class. 我很难弄清楚编程1课的家庭作业的答案。 The assignment is prompt a user for input (up to 4 bits) in binary, and convert it to the decimal equivalent. 该分配提示用户输入二进制(最多4位),并将其转换为等效的十进制数。 Using loops, conditional statements, ParseInt, and anything other than the modulus operator and other math operators are not allowed. 不允许使用循环,条件语句,ParseInt以及除模运算符和其他数学运算符以外的任何内容。

I am having trouble with the mathematical aspect, I think once I understand how to use the modulus operator to answer the question I would be able to write the code for it. 我在数学方面遇到了麻烦,我想一旦我了解了如何使用模运算符来回答这个问题,我便可以为其编写代码。

I have searched and have not been able to find anything that was able to help. 我已经搜索过,但是找不到任何能够帮助您的东西。

You should be getting the number values of each position and add them using the power of 2 to get back the original number. 您应该获取每个位置的数字值,并使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM