0
Binary to decimal
Please help me with the code for converting binary to decimal using loops and converting by means of the subtraction method
2 Réponses
+ 4
Look at Sololearn's codes. Ruby offers nice solution https://code.sololearn.com/c5s1ub3Lz5pG/?ref=app so as Sololearn's cpp alternative.
0
Try this program :
//BInary notation to decimal notation
#include <iostream>
#include <cmath>
using namespace std ;
int main ()
{
// declaring variable x ,z as an int
int x , z ;
// setting variable y to a constant integer
const int y = 2 ;
int dec = 0 ; // setting variable dec to 0
int bin [4] ; // declaring an array of size 4
// loading the array
bin [0] = 1 ;
bin [1] = 0 ;
bin [2] = 1 ;
bin [3] = 1 ;
// DIsplaying the array
for ( x = 3 ; x >= 0 ; x-- )
cout << bin [x] << " " ;
// BInary to decimal conversion
for ( x = 0 ; x <= 3 ; x++ ) {
// setting z to power ( base , exponent )
z = pow ( y , x ) ;
// if condition is true the dec = dec + z
if ( bin [x] ) dec += z ;
}
// displaying the value of dec
cout << " - " << dec ;
return 0 ;
}
Note : The decimal is obtain by adding each exponent that are true .