after the loop ends the value of my "dec" variable changes could you figure it out?
#include %26lt;iostream%26gt;
#include %26lt;conio.h%26gt;
using namespace std;
int main()
{
int dec; //holds decimal value of an 8 bit binary
int pow2; //power of 2
cout%26lt;%26lt;"Enter 8 bit binary: ";
for(int x=0 , dec=0 , pow2=128 ; x%26lt;8 ; ++x , pow2/=2)
{
if(((static_cast%26lt;int%26gt;(getche())-48) == 1)) // get int value of char and compare to 1
dec+=pow2; // if 1 then add power of 2 to decimal
/*cout%26lt;%26lt;'\n'%26lt;%26lt;dec%26lt;%26lt;'\t'%26lt;%26lt;pow2%26lt;%26lt;endl;*/
}
cout%26lt;%26lt;" is equal to "%26lt;%26lt;dec%26lt;%26lt;endl;
}
remove the comments to see that the value correct while looping only. Sorry if the code is hard to understand|||Hi,
The "dec" identifier is reserved for something else in C++ and you're getting a conflict.
Cheers,
Bogdan|||I don't know why but when I restructured the for loop I got correct results!
dec = 0;
pow2 = 128;
for(int x=0 ; x%26lt;8 ; x++ )
{
if(((static_cast%26lt;int%26gt;(getche())-48) == 1)) // get int value of char and compare to 1
dec+=pow2; // if 1 then add power of 2 to decimal
// cout%26lt;%26lt;'\n'%26lt;%26lt;dec%26lt;%26lt;'\t'%26lt;%26lt;pow2%26lt;%26lt;endl;
pow2 /= 2;
}
+add
Love4Boo is correct. It's a manipulator function that's used with cout to set the base. The link is to the cplusplus reference.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment