我正在编写一个将十进制数转换为二进制和十六进制的 C++ 程序。 问题在于,出于某种原因,它每次都将数字“1875954912”连接到两种表示形式。
我已经尝试了很多东西 - 主要是改变程序计算 numArrayLength 的方式和我的 decToBase 函数中的 for 循环,但我还没有弄清楚为什么会发生这种情况。
顺便说一下,该程序还不完整——它还没有将大于 9 的整数转换为十六进制表示的字母,但这不是我现在主要关心的问题。
这是我的代码:
#include <iostream>
#include <cmath>
using namespace std;
int howManyBitsNeeded(int someNum, int base) {
int numOfDivisions = 0;
while (someNum != 0) {
someNum = floor(someNum / base);
numOfDivisions += 1;
}
return numOfDivisions;
}
int decToBase(int someNum, int base) {
int bitsNeeded = howManyBitsNeeded(someNum,base);
int numArrayLength = bitsNeeded;
int numArray[bitsNeeded];
while (bitsNeeded > 0) {
numArray[bitsNeeded] = (someNum % base);
someNum = floor(someNum / base);
bitsNeeded -= 1;
}
for (int k = (numArrayLength-1); k >= 0; --k) {
cout << numArray[(numArrayLength - k)];
}
}
int main() {
int inpNum;
cout << "Enter your number: ";
cin >> inpNum;
cout << "Binary representation: " << decToBase(inpNum,2) << endl;
cout << "Hexadecimal representation: " << decToBase(inpNum,16);
return 0;
}
输出结果如下:
Enter your number: 25
Binary representation: 110011875954912
Hexadecimal representation: 191875954912
如有任何帮助,我们将不胜感激!
最佳答案
您的 decToBase
被声明为返回一个 int
,但它实际上并没有返回任何东西。您的编译器应该警告您这一点。由于您未在此处返回任何内容,因此将其返回类型更改为 void
。然后不要尝试打印它的返回值,只需调用函数而不打印它:
std::cout << "Binary representation: ";
decToBase(inpNum, 2); // this already prints the number, no need to pass it to std::cout
std::cout << endl;
std::cout << "Hexadecimal representation: ";
decToBase(inpNum, 16);
std::cout << std::endl;
当然,您也可以更改函数以返回要打印的字符串,而不是在函数内部打印它。
还有一个问题:
int numArray[bitsNeeded];
当您尝试在此处访问它时,它超出了范围:
while (bitsNeeded > 0) {
numArray[bitsNeeded] = (someNum % base);
稍后当您尝试打印它时。要通过一个错误摆脱它,您必须将其更改为
numArray[bitsNeeded-1] = (someNum % base);
然后在输出中将其更改为
cout << numArray[(numArrayLength - k -1)];
当您使用它时,与其将其作为 VLA ( which isn't part of C++ and only works if the compiler tolerates it),我建议您使用 vector :
std::vector<int> numArray(bitsNeeded+1); // include <vector> for this to work
此外,请注意整数除法已经被截断,因此除非您打算稍后支持负数,否则您可以通过以下方式消除有关隐式 double
到 int
转换的警告改变这个:
someNum = floor(someNum / base);
对此:
someNum /= base;
关于C++:添加到输出中的不需要的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58554574/