binary to decimal converter, needed code review

basically almost everything works, besides the output
my output is 2 less than it should be.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
 char again = '1' ;
  int const size = 8 ;
int num[size] ;
int i ;
int decimal ;




do { 
cout << "enter num " << endl ;
      for ( i= size ; i >=0 ; i--)
    {
        cout << " your num" <<endl ;
        cin >> num[i] ;
        cout << endl ;
    }

//  ------------------- to decimal

cout << "displayin nums entered " << endl ;
    for (i=0 ; i<8 ; i++)
    {
    cout << num[i] << "  " ;
    }

    
    for (i=0 ; i<8 ; i++)
    {
        decimal += num[i] * pow(2.0, i) ;
        
        }
        
        cout << "ur decimal " << decimal << endl ;  






cout << "stop " << endl << endl << endl ;
      
 // ----------------- end of the program
 
cout <<  "To stop press 1 " << endl ;
cin >> again ;
 
}
 while (again != 1)     ;



displayin nums entered
0  0  0  1  1  1  1  1  ur decimal 246
stop




Last edited on
decimal is uninitialized to begin with.
i initialized decimal, however i keep getting "call of overloaded `pow(int, int&)' is ambiguous " error
either using 2 or 2.0
char again = '1' ;
int const size = 8 ;
int num[size] ;
int i ;
int decimal = 0;

do{
cout << "enter num " << endl ;
for ( i = size - 1 ; i >= 0 ; --i) //your original loop is out of scope!!! num[0] ~ num[7] not num[8] ~ num[0]
{
cout << " your num" <<endl ;
cin >> num[i] ;
cout << endl ;
}

// ------------------- to decimal

cout << "displayin nums entered " << endl ;
//I change the order of displaying, this makes thing easier
for (i = size - 1 ; i >= 0 ; --i)
cout << num[i] << " " ;

for (i = size - 1; i >= 0; --i)
decimal += num[i] * pow(2.0, i) ;

cout << "ur decimal " << decimal << endl ;
cout << "stop " << endl << endl << endl ;

// ----------------- end of the program

cout << "To stop press 1 " << endl ;
cin >> again ;

}
while (again != '1'); //not again != 1

ps: you could consider about the "bitset" class

#include<iostream>
#include<bitset>
using namespace std;

int main()
{
const int SIZE = 8;
bitset<SIZE> num;

cout<<"enter your number"<<endl;
cin>>num;
cout<<"your number = "<<num<<endl;
cout<<"decimal value = "<<num.to_ulong()<<endl;

cin.get();
}
Last edited on
how could you post your code like that?thanks
[code]your code here[/code]

http://cplusplus.com/articles/firedraco1/
Last edited on
m4ster r0shi, thanks a lot
@StereoMatching
i never used "bitset" class, but it seems to work, so i guess i need to google on it.
Thank you.
Topic archived. No new replies allowed.