I'm stuck with an error message that neither I nor any of my computer science peeps can understand. The program I wrote is meant to be a simple decimal to binary converter, but with this message it's more complicated than I thought.
Here's the code:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int num = 0;
double k = 0;
int max = 0;
bool binary[100];
cout << "Enter a decimal number: " ;
cin >> num;
while (pow(2,k) <= num)
k++;
k--; // Decrements the power after the highest power of 2 is found.
max = k;
while (k >= 0 && num > 0)
{
if (pow(2,k) > num)
binary[k] = 0;
else
{
binary[k] = 1;
num -= pow(2,k);
}
k--;
}
while (max >= 0)
{
cout << binary[max];
max++;
}
return 0;
}
The error exactly says:
...\dectobin.cpp:27: error: invalid types 'bool [100][double]' for array subscript
...\dectobin.cpp:30: error: invalid types 'bool [100][double]' for array subscript
If it helps, I'm using Quincy... but only because my lecturer is using Quincy.
Any help is appreciated greatly.
PS, is there any reason why the variable k can't be of type int?
There's no such thing as array[3.14159]. It has to be a whole integer. So floating point numbers as array indexes make no sense.
You could make k an integer, and it'd spew warnings, but it'd work. Using pow() is severe overkill, though -- your numbers are already binary. Just use binary operators to get at the bits in num instead of converting to float, doing exponents, and converting back.
#include <iostream>
#include <cmath>
using namespace std;
int main(void)
{
unsigned int num, q;
cout << "Enter a decimal number: " ;
cin >> num;
for(q=31; q >= 0; q--)
{
// Shift the number q bits to the right, then check if bit 1 is set.
if((num >> q) & 1) cout << "1";
else cout << "0";
}
return(0);
}
Although I would very much like to do this, the binary equivalent has to be stored within an array... =[
Also, I actually did declare k as type int before, but that produced even more problems for me... it said on lines 14, 22 and 27:
error: call of overloaded 'pow(int, int&); is ambiguous
note: candidates are: double pow(double, double)