c++ - just correcting
- Artur (57/57) Dec 01 2008 /*This prog supposed to convert from binary number system to decimal but
- Bertel Brander (8/11) Dec 01 2008 There is two things to notice.
- %u (3/3) Dec 08 2008 try->
- Cesar Rabak (5/37) Dec 10 2008 Of course. Get a look on your reference material about the "short
/*This prog supposed to convert from binary number system to decimal but something is not working properly please help*/ #include <iostream> using namespace std; int main() { int a[8],sum=0; cout << endl; cout << "Input Binary number(with spaces between digits): "; for(int i=0;i<=7;i++) { cin >> a[i]; if((a[i]!=1)&&(a[i]!=0))//Strange indeed!!! I tried || but my message showed up. { cout << "You entered wrong digit!!!" << endl; i--; } } for(int i=0;i<8;i++) // I also tried for(int i=7;i>=0;i--) but get same results { // results of 000000001 is 128 and of 10000000 is 1?! if(a[i]) { switch(i) // ofcourse I can just change cases but it is not the way "for" must work... { case 0: sum+=1; break; case 1: sum += 2; break; case 2: sum += 4; break; case 3: sum += 8; break; case 4: sum += 16; break; case 5: sum += 32; break; case 6: sum += 64; break; case 7: sum += 128; break; default: cout << "This shall not happen!" << endl; } } } cout << sum; }
Dec 01 2008
Artur skrev:/*This prog supposed to convert from binary number system to decimal but something is not working properly please help*/There is two things to notice. First, when you enter the number you must have a space or an enter between the numbers, otherwise it will see it as one big numer. Second, the program seems to handle the digits backwards, if i enter 1 0 0 0 0 0 0 0, the answer is 1, whereas get me 128.
Dec 01 2008
Artur escreveu:/*This prog supposed to convert from binary number system to decimal but something is not working properly please help*/ #include <iostream> using namespace std; int main() { int a[8],sum=0; cout << endl; cout << "Input Binary number(with spaces between digits): "; for(int i=0;i<=7;i++) { cin >> a[i]; if((a[i]!=1)&&(a[i]!=0))//Strange indeed!!! I tried || but my message showed up.Of course. Get a look on your reference material about the "short circuiting" property of the operators && and ||.{ cout << "You entered wrong digit!!!" << endl; i--; } } for(int i=0;i<8;i++) // I also tried for(int i=7;i>=0;i--) but get same results { // results of 000000001 is 128 and of 10000000 is 1?!In order you can grok what's happening, try to print the digits in the loop. Will it make sense?
Dec 10 2008