+ 1
Code is having logical errors. Please help!
I had made a code to convert a binary number to decimal but i think some logical errors are there. Can you help me out? I am just a beginner, would be glad if you help. #include <iostream> #include <cmath> using namespace std; int main() { int bin,pwr=1,result=0; cout<<"Type only binary value"; cin>>bin; while (bin>=0) { if (bin%10==1) {result+=pow(2,pwr);} else if (bin%10==0) {result+=0;} bin=bin/10; pwr++; } cout<<result; return 0; }
1 ответ
+ 6
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int bin, pwr = 0, result = 0;
cin >> bin;
cout << "Binary value: " << bin << endl;
while(bin > 0)
{
int rem = bin % 10;
if(rem == 1)
{
int sq = pow(2, pwr);
result += sq;
}
bin /= 10;
pwr++;
}
cout << "\nDecimal value: " << result << endl;
return 0;
}