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;
}

Recommended Answers

All 4 Replies

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().

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;
}

Please take a look at how the c_str function is used.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.