简体   繁体   English

使用for循环将小数转换为二进制?

[英]Coverting a decimal to binary using for loops?

I'm trying to write a program that converts decimal to binary and decimal to octal. 我正在尝试编写一个将十进制转换为二进制并将十进制转换为八进制的程序。 I can convert from decimal to binary, but from decimal to octal it just doesn't work. 我可以从十进制转换为二进制,但是不能从十进制转换为八进制。

import java.util.*;
public class RadixConversion 
{
public static void main(String[] args) 
{
Scanner scan = new Scanner(System.in);    
System.out.println("Enter a number: ");
int number = scan.nextInt();
System.out.println("Convert to base: ");
String letter = scan.next();

if (letter.equals("b")||letter.equals("B"))
    {
        int remainder = 0;
        for (int i = 1; number > 0; i++) 
        {
        number /= 2;
        remainder = number % 2;
        System.out.print(remainder);
        }
    }


    else if (letter.equals ("o") || letter.equals ("O"))
    {
        int remainder = 0;
        for (int i = 1; number >0 ; i++) 
        {
        number /= 8;
        remainder = number % 8;
        System.out.print(remainder);
        }
    }
 }        
 }

This is a bit more complicated the way I learned it. 这是我学习的方式有点复杂。 You have to find the largest power of 8 that fits in the number, see how many times it goes into the number, and repeat the process with the next lowest power of 8. You print each digit as you go. 您必须找到适合该数字的8的最大幂,查看该数字有多少次,然后以8的下一个最低幂重复该过程。随行打印每个数字。

neither one looks to be generating the correct value, it would just be less obvious with 0's and 1's. 看上去都没有人产生正确的值,而0和1不会那么明显。 You are dropping the first digit and printing the digits in reverse order (the one's digit get printed first) 您要删除第一个数字并以相反的顺序打印数字(一个人的数字首先打印)

    int remainder = 0;
    String result = "";
    for (int i = 1; number >0 ; i++) 
    {
      remainder = number % 8;
      result = remainder + result;  // remainder first puts the digits in the right order
      number /= 8;
    }
    System.out.print(result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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