我在尝试使用 C++ 构建器运行此代码时遇到错误。 该代码应该将给定的数字转换为相应的数字系统,但是,我不断收到错误:范围检查错误; 我不明白,因为代码在控制台中运行得很好,直到我决定将其放入 C++ 构建器中来构建 GUI。
我尝试通过检查是否没有来自前端的输入来进行调试,但这不是问题,然后我尝试在 for 循环中添加更多条件,尝试使用 AI 来查看问题出在哪里我仍然遇到同样的错误,有人帮忙! 这是功能:
String convertNumber(String number, int fromBase, int toBase) {
// Check if the bases are valid (between 2 and 36)
if (fromBase < 2 || fromBase > 36 || toBase < 2 || toBase > 36) {
return "Invalid base";
}
// Step 1: Convert the input number (in 'fromBase') to a decimal (base 10) number
int64_t decimalValue = 0;
for (int i = 1; i <= number.Length(); i++) { // 1-based indexing
int digitValue;
Char currentChar = number[i - 1]; // 0-based access for characters
// Check if the character is a digit or letter and get the digit's value
if (isdigit(currentChar)) {
digitValue = currentChar - '0'; // Convert character '0'-'9' to digit 0-9
} else if (isalpha(currentChar)) {
digitValue = toupper(currentChar) - 'A' + 10; // Convert 'A'-'Z' to 10-35
} else {
return "Invalid character in input"; // Handle invalid characters
}
// Check if digit value is valid for the base
if (digitValue >= fromBase) {
return "Invalid digit for the given base";
}
// Convert to decimal value (manual calculation of power of the base)
decimalValue = decimalValue * fromBase + digitValue;
}
// Step 2: Convert the decimal value to the target 'toBase'
String result = "";
if (decimalValue == 0) {
return "0"; // Edge case: if the number is zero, return "0"
}
while (decimalValue > 0) {
int remainder = decimalValue % toBase;
// Convert the remainder to the corresponding character
if (remainder < 10) {
result = String((char)(remainder + '0')) + result; // For digits 0-9
} else {
result = String((char)(remainder - 10 + 'A')) + result; // For letters A-Z
}
decimalValue /= toBase;
}
return result;
}
正如评论中提到的,C++Builder 的
System::String
类型是 1 索引的,但您的代码假设它是 0 索引的。
由于您的循环使用基于 1 的索引计数器,因此只需更改此行:
Char currentChar = number[i - 1];
为此:
Char currentChar = number[i];