-
Possible loss of data?
I'm new to C++ and was trying to write a program that would ask for a number then return its binary form. However I couldn't get it to compile while trying to use integer powers, and had to use a double power function...however got a warning saying that there could be possible loss of data. After running the program a few times it seems to be fine, but how can I avoid the warning? Here is my code:
Code:
#include "base10tobase2.h"
using namespace std;
int main()
{
int i,x=-1;
double a;
while ((x<0)||(x>255))
{
cout<<"Please enter a number less than 256:\n";
cin>>x;
}
cout<<"The number you entered was "<<x<<"\n";
cout<<"Its binary form is:\n";
for (i=7;i>-1;i--)
{
a=pow(2.0,i);
if ((x-a)>-1)
{
x-=a;
cout<<"1";
}
else
cout<<"0";
}
cout<<"\n\nPress enter to continue";
fflush (stdin);
cin.get();
return 0;
}
Also, as I am new to C++, I would appreciate any tips/advice you have?
Thanks!
-
Basically, it's telling you that by assigning a double to an int, you're losing precision.
Using pow() for this is wrong anyway. To get powers of two, you use bit shifting.
-
The warning probably come from this line:
x is an int, but a is a double, which can store a wider range of values than an int. If you really want this conversion to happen, you should document it with a type cast:
Code:
x -= static_cast<int>(a);
A few more things to note:
1. You are using cout, cin and pow, so you should #include <iostream> and <cmath>. They might have been included in "base10tobase2.h", but it is better to include them, just in case.
2. You should indent your code more consistently.
3. fflush(stdin) is undefined. Use cin.ignore() instead.
EDIT:
Ah yes, but since you can use CornedBee's suggestion, it would be better not to use pow and the type cast in the first place, upon which you also would not need to #include <cmath>.
-
Thankyou, I will make those changes (and look up bit shifting!). Thanks for the quick response!
-