954,170 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

If statement confusion

#include <iostream>
#include <iomanip>
using namespace std;
int main() 
{
	// Variables for used for user input
	int nbase;


	//  Users input is needed but no error checking is done as per lab instuctions
	cout << "Please enter your choice for conversion.  The letter O for octal OR B for binary!" << endl;
	cin >> nbase;

	if (nbase == 2 || nbase == 8)
	{
		int total;
		int r3;
		int r2;
		int r1;
		int r0;
		int convert;
		// char lbase;
		cout << "Please enter your four digit number!" << endl;
		cin >> total;

		//  The below math calculations break down the full four digit number so the user does not 
		//  have to enter 4 individual numbers.
		r3 = total / 1000;
		total = total - (r3 * 1000);
		r2 = total / 100;
		total = total - (r2 * 100);
		r1 = total / 10;
		total = total - (r1 * 10);
		r0 = total;
		
		if  (nbase == 2 && r3 && r2 && r1 && r0 <= 1 && r3 && r2 && r1 && r0 >= 0)
		{
			// This coverts the users numbers into the base specified earlier
			convert = nbase * nbase * nbase * r3 + nbase * nbase * r2 + nbase * r1 + r0;
			cout << "Your number converted to decimal is " << convert << endl;
		}
		else if (nbase == 8 && r3 && r2 && r1 && r0 <= 7 && r3 && r2 && r1 && r0 >= 0)
		{
			// This coverts the users numbers into the base specified earlier 
			convert = nbase * nbase * nbase * r3 + nbase * nbase * r2 + nbase * r1 + r0;
			cout << "Your number converted to decimal is " << convert << endl;
		}
		else
		{
			cout << nbase << r3 << r2 << r1 << r0 << endl;
			cout << "You did not enter a valid number, try again" << endl;
		}
	}
	else
	cout << "You did not enter 2 or 8, try again" << endl;

	cin.get();
	return 0;
}


I'm having trouble on lines 36 and 42 of my code. No errors occur when I compile but I cannot get line 36 and 42 to work the way I want. When I pick 1010 for my four digit binary number it does not work but 1111 works fine. I already tried to cout all my variables around line 35 just before the If statement so I can make sure nothing is assigned incorrectly. All my variables seem to be alright and when I work out the math portion on paper it seems to be ok. Any advice would be appeciated.

Tjvelcro
Newbie Poster
1 post since Oct 2009
Reputation Points: 10
Solved Threads: 0
 

If you intend to check if each r value is less than or equal to 1 then you must say

if(r3 <= 1 && r2 <= 1 && r1 <= 1 && r0 <= 1 )...

Do this for each of your statements that are not working correctly.
This should resolve your problem.
Is this your problem?

Grn Xtrm
Posting Pro in Training
495 posts since Nov 2008
Reputation Points: 100
Solved Threads: 48
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You