so i have spent 3 hours trying to figure out how exponents work in C++ but now. my if statement isnt working. even if i punch in a 0 it spits out 1
thanks in advance

#include<iostream>
#include<string>
#include<cmath>
using namespace std;
void binToDec(string getBinary);
void main()
{
	string getBinary;
	cout<<"Enter a Binary Number:"<<endl;
	cin>>getBinary;
	binToDec(getBinary);
	

}
void binToDec(string getBinary)
{
	int setLength,total=0;
	double placeholder=0;
	setLength=getBinary.size();
	
	for(int i=setLength;i>0;i--)
	{
		int num=pow(2.0,placeholder);
		int test=getBinary[i];
		if (test=1)
		{
			total=total+num;
		}

		placeholder=placeholder +1;
	cout<<total<<endl;
	}
	


}

Recommended Answers

All 8 Replies

1) Comparison of test with 1 has two equals signs, not 1 if (test == 1) . Having one equals sign assigns test to 1.

2) main() returns int, not void. Wash your mouth out with soap for returning void.

Hmmm shouldn't
if (test=1)
be
if (test == 1)

Anyway I read that it isn't good to have void main().

haha im just making small programs for class thanks for the help. stupid mistake

It still won't work. You are comparing char with int:
getBinary is char, and 1 is int.
char != int!!!

It still won't work. You are comparing char with int:
getBinary is char, and 1 is int.
char != int!!!

It will work. Comparing char with int is allowed.

Worst case is a compiler warning (eg mismatch of precision of operands). A compiler warning means the programmer should check and make sure the code has the intended result, not that it is disallowed.

It will work. Comparing char with int is allowed.

Worst case is a compiler warning (eg mismatch of precision of operands). A compiler warning means the programmer should check and make sure the code has the intended result, not that it is disallowed.

Yes, but does he want to compare test with '1' or with 1? Because that's different thing!

Yes, but does he want to compare test with '1' or with 1? Because that's different thing!

Ah, yes. Good point. Something for the original poster to contemplate .....

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.