gpt4 book ai didi

java - charAt() 和 Math.pow()

转载 作者:行者123 更新时间:2023-12-01 22:33:26 25 4
gpt4 key购买 nike

背景:

我正在为类作业制作一个简单的基础转换器。我相当接近完成,但需要整理转换算法以将用户输入的值(在给定的基数中)转换为基数 10 的值。

尝试:

import java.util.Scanner;

public class BaseConverter {
public static void main(String[] args) {
String numIn, intro1, prompt1, prompt2, output1;
int baseIn;
double numOut;
boolean flag = true;
Scanner kb = new Scanner(System.in);

intro1 = "This program converts values in different number bases to a decimal value.";
prompt1 = "Type in a number base (2 - 9): ";

while (flag == true){
System.out.println(intro1);
System.out.println(prompt1);
baseIn = kb.nextInt();
//Checking base value for outliers outside given range
if (baseIn < 2 || baseIn > 9) {
System.out.println("Base must be between 2 and 9");
System.exit(1);
}
prompt2 = "Type in a base "+baseIn+" number: ";
System.out.println(prompt2);
numIn = kb.next();

// System.out.println(numStore);
int counter = 0;
// Let's pretend baseIn is 3 and i starts at 3
for (int i = numIn.length(); i >= 1; i--){
numOut = (numIn.charAt(i-1) * Math.pow(baseIn, counter++));
System.out.println(numOut);
}
}//while
}// method
}//class

问题:

这一行没有返回预期的值

numOut = (numIn.charAt(i-1) * Math.pow(baseIn, counter++));

例如,在字符串“10”中,numOut 在 for 循环的第一次迭代中应为 (0*(2*0)) 或零。相反,它返回 48.0。

我的想法:

我暗暗怀疑它与 charAt() 方法有关,因为调试 Math.pow() 方法显示它返回预期值。假设它与所有不同的变量类型有关?我不确定。

最佳答案

是的,你是对的 charAt 是问题所在。

当您键入“10”时,根据编码表 Java,字符 '0' 的整数值为 48,对于 '1' 则为 49用于对字符进行编码。

enter image description here

如果你看一下,你会发现 0 被编码为 0x0030 = 3*16^1 = 48,1 被编码为 0x0031 = 3*16^1 + 1* 16^0 = 49 等等。

如果你想获取字符本身的数值你可以使用

numOut = Character.getNumericValue(numIn.charAt(i-1)) * Math.pow(baseIn, counter++);

关于java - charAt() 和 Math.pow(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28444501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com