i dont knw why i am not getting the right ans

can someone help?

#include<iostream>
#include<string>
#include<cmath>


using namespace std;

int main()
{
	int sum=0;
	string val;

	

	cout<<"enter a binary number:"<<endl;
	cin>>val;
	
	
	for(int i=0;i<val.size();i++)
	{
		cout<<val[i];
	}

	for(int i=1;i<val.size();i++)
	{
		int x = val.size();
		sum+=val[x-i]*pow(2.0,i-1);
	}

	cout<<sum;


	return 0;
}

The first problem is your indicies are off on sum+=val[x-i]*pow(2.0,i-1); Write it out on paper, in an example with an 8 digit number, you want:
val[0] times 2^7+ val[1]*2^6 etc which means you also need to change where the for loop begins. Put some couts in there to see how values progress as the loop proceeds.

Also, since val is a string, what value would an element have if it were '1' or '0'. A hint, it's not 1 or 0. Your string holds characters which have an ASCII value associated with them. A simple solution is to subtract '0' from the character value.

It's not consequential but sum should probably be a double as that is what is coming back from pow().

Edited 6 Years Ago by jonsca: n/a

okey i made some changes to my code .....now i am converting my C++ string to c style .....but when i debug it i can see it is not happening

what can be a reason behind it?

#include<iostream>
#include<string>
#include<cmath>
#include<cstring>

using namespace std;

int main()
{
	double sum=0;
	string val;

	
	
	cout<<"enter a binary number:"<<endl;
	cin>>val;
	int x= val.size();

	val.c_str();
	

	for(int i=1;i<x;i++)
	{
		sum+=val[x-(i+1)]*pow(2.0,i);
	}

	cout<<sum;


	return 0;
}

okay so i finally i figured it out so it was all about subtracting that character '0' .......but i still dont know why converting string to c style string was not successful.

this my working code:

#include<iostream>
#include<string>
#include<cmath>
#include<cstring>

using namespace std;

int main()
{
	double sum=0;
	string val;

	
	
	cout<<"enter a binary number:"<<endl;
	cin>>val;
	int x= val.size();

	//val.c_str();
	

	for(int i=0;i<x;i++)
	{
		sum+=(val[x-(i+1)]-'0')*pow(2.0,i);
	}

	cout<<sum;


	return 0;
}
This article has been dead for over six months. Start a new discussion instead.