Java 使用%和/操作数将base10数字转换为另一个基数
我的教授让我们创建一个程序,将一个以10为基数的数字转换成另一个基数。他给了我们这些指示: 首先计算位置0——单位位置。记住这是第一个除法,所以当基数10除以基数(提示%)时,它是余数。然后计算商(整数除法/就可以了!)。您可以将结果存储回base10Num,也可以为商声明一个新变量。现在计算place1——这是前一步的商除以基数后的余数。然后计算新的商。重复上面的想法,计算place2和下一个商。再次重复以计算位置3 我目前的代码是:Java 使用%和/操作数将base10数字转换为另一个基数,java,Java,我的教授让我们创建一个程序,将一个以10为基数的数字转换成另一个基数。他给了我们这些指示: 首先计算位置0——单位位置。记住这是第一个除法,所以当基数10除以基数(提示%)时,它是余数。然后计算商(整数除法/就可以了!)。您可以将结果存储回base10Num,也可以为商声明一个新变量。现在计算place1——这是前一步的商除以基数后的余数。然后计算新的商。重复上面的想法,计算place2和下一个商。再次重复以计算位置3 我目前的代码是: package baseconversion; impor
package baseconversion;
import java.util.*;
public class BaseConversion
{
public static void main (String[] args)
{
int base; // the new base
int base10Num; // the number in base 10
int maxNumber; // the maximum number that will fit
// in 4 digits in the new base
int place0; // digit in the 1's (base^0) place
int place1; // digit in the base^1 place
int place2; // digit in the base^2 place
int place3; // digit in the base^3 place
int quotient0;
int quotient1;
int quotient2;
String baseBNum = new String (""); // the number in the new base
Scanner scan = new Scanner(System.in);
System.out.println();
System.out.println ("Base Conversion Program");
System.out.println();
System.out.print ("Please enter a base (2 - 9): ");
base = scan.nextInt();
System.out.print ("Please enter a base 10 number to convert: ");
base10Num = scan.nextInt();
place0 = base10Num%base;
quotient0 = base10Num/base;
place1 = quotient0%base;
quotient1 = place1/base;
place2 = quotient1%base;
quotient2 = place2/base;
place3 = quotient2%base ;
baseBNum = Integer.toString(place0) + Integer.toString(place1) + Integer.toString(place2) + Integer.toString(place3);
System.out.println(baseBNum);
}
}
当base10Num=13和base=2时,我的教授说baseBNum应该等于1101。尽管如此,我还是得到了1000作为我的基准值。按照我教授的指示,我应该怎么做来修复我的代码?我可能会疯了,但我觉得你的代码看起来不错,你确定这就是你得到的输出吗?你有没有试着一步一步地调试你的代码,看看所有变量是否都有正确的值?我想你完全是理智的,我的人。我又试了一次,结果还是得到了1000。我检查过了,所有变量都应该得到正确的值。代码可能是对的,这不是我的教授第一次胡闹了。