GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 08-Oct-2005, 16:42
Elsydeon Elsydeon is offline
Junior Member
 
Join Date: Aug 2005
Posts: 45
Elsydeon is on a distinguished road

Hitting a logic problem I can't solve


Well, my last lab needs a few tweaks before I can start the next one. It's fairly straightforward, I just can't see why it's doing what it's doing.

CPP / C++ / C Code:
// rationl2.cpp   interface and implementation for class rational
// whats new?  implementation for reduce, add

#include "rat5Nest.h"
#include <cstring>
#include <string.h>
#include <stdio.h>


const int
	nameLength = 4,
	maxStocks = 50;						// maximum number of stocks

struct stockType {					// data about a stock
 char name[nameLength];			// 3 or 4 letter stock code (ex: IBM)
 float buyAt,								// purchase price per share
	sellLow,									// when it goes below this price, sell?
	sellHigh;									// when it goes above this price, sell?
 rational numShares;				// number of shares held
 // date datePurchased;			// add when date object purchased
}; // stockType

class portfolioClass {
	// holds an array of stockType
	// conditions maintained in object:
	//	 stock ordered by name
	//	 no repetitions
	public:
		portfolioClass();							// constructor
		void addStock (stockType stock);	// adds stock if it does not exist
		void deleteStock (char code[nameLength]);
							// deletes stock with code = name.
		void findStock (char code[nameLength], stockType &stock);
							// returns stock with name = code
		void updateStock (stockType stock);
							// locates and replaces current entry with stock
		bool allOK ();	// returns the value of ok, then resets it to yep
		void print (char code[nameLength]);
		void printPort();
		int howManyStock();					// returns the number of stock in portfolio
	private:
		stockType data[maxStocks];
		int numActive;		// number of active records in data
		bool ok;				// holds yep until an operation fails
		//void locateStock (char code[nameLength], int &spot, bool &exactMatch);
}; // stockType class

portfolioClass::portfolioClass() // constructor
{	
	numActive=0;
	ok=true;

}

bool portfolioClass::allOK () { //returns true if ok is true and false if ok is false
	if (ok)
		return true;
	else
		return false;
	ok=true;
}

void portfolioClass::updateStock (stockType stock) { //uses "stock" to replace the instance in
													//the portfolio with the matching name.
	int i=0, loc=0;
	bool fin=0;
	do {
		if (!strcmp(stock.name, data[i].name)) {
			fin=1;
			data[i] = stock;
		}
		i++;
	} while ((!fin)&&(i<=numActive));


}

void portfolioClass::addStock (stockType stock) { //adds "stock" to data alphabetically.
	int count=numActive-1;
	int z=0;
	
	if(numActive>0){
		do{
			if(strcmp (stock.name,data[count].name)== -1){
					data[count+1]=data[count];
					count--;
				}
			else{
				data[count+1]=stock;
				numActive++;
				z=1;
			}
		}while(z!=1);
	}
	if(numActive<=0){
		data[0]=stock;
		numActive++;
	}
}

void portfolioClass::findStock (char code[nameLength], stockType& stk) { //sets stk to the Portfolio
																		//stock with the same name.
	int i=0;
	bool fin=0;
	do {
		if (!strcmp(code, data[i].name)) {
			fin=1;
			stk = data[i];
		}
		i++;
	}
		while ((!fin)&&(i<=numActive));
}

void portfolioClass::deleteStock (char code[nameLength]) { //deletes stock in portfolio with 
															//given name.
	stockType stock;
	int i=0;
	bool fin=0;
	do {
		if (!strcmp(code, data[i].name)) {
			for (int j=i; j<=numActive; j++)
				data[j]=data[j+1];
			fin=1;
			numActive--;
		}
		i++;
		} while ((!fin)&&(i<=numActive));
	if (fin=0)
		cout << "no match found. \n";
}

int portfolioClass::howManyStock () { //returns the number of active stock
	return numActive;
}
void portfolioClass::print (char code[nameLength]) { //prints stock matching code
		int i=0;
	bool fin=0;
	do {
		if (!strcmp(code, data[i].name)) {
			i--;
			fin=1;
		}
		i++;
		} while ((!fin)&&(i<=numActive));
	if (fin=0)
		cout << "no match found. \n";
	cout << data[i].name << endl;
	cout << data[i].buyAt << endl;
	cout << data[i].sellLow << endl;
	cout << data[i].sellHigh << endl;
	cout << (data[i].numShares.returnNumerator ()) << "/" << (data[i].numShares.returnDenominator ()) << endl;
}

void portfolioClass::printPort(){
	for(int g=0;g<numActive;g++){
		cout << endl<<"Name: "<<data[g].name << endl;
		cout << "Buy At: "<<data[g].buyAt << endl;
		cout << "Sell Low: "<<data[g].sellLow << endl;
		cout << "Sell High: "<<data[g].sellHigh << endl;
		cout << "Owned/Total: "<<(data[g].numShares.returnNumerator ()) << "/" << (data[g].numShares.returnDenominator ()) << endl;
	}
}

void main () {
	int input, input2;
	stockType stk, stk2;
	char name[nameLength], name2[nameLength], name3[nameLength];
	int num, den, num2, den2;
	bool ok=1;

	cout << "Stock Portfolio Management System \n\n";
	portfolioClass portfolio1;
	do {
	cout << "You have " << portfolio1.howManyStock() << " stocks. What would you like to do?" << endl;
	cout << "1. Add new stock to your portfolio \n";
	cout << "2. Delete stock from your portfolio \n";
	cout << "3. Update stock in your porfolio \n";
	cout << "4. View stock in your portfolio \n";
	cout << "5. Quit \n";
	
		cin >> input;
		switch (input)
		{
		case 1:

			do {
			cout << "Enter the name of the stock. \n";
			cin >> name;
			if (strlen(name)>nameLength)
				cout << "Too long. Please try again. \n";
			} while (strlen(name)>nameLength);
			strncpy (stk.name, name, nameLength);
			cout << "Enter the price per share. \n";
			cin >> stk.buyAt;
			cout << "Enter the Low sell price. \n";
			cin >> stk.sellLow;
			cout << "Enter the High sell price. \n";
			cin >> stk.sellHigh;
			do {
			cout << "Enter the number of shares purchased. (numerator) \n";
			cin >> num;
			cout << "Enter total number of shares available. (denominator) \n";
			cin >> den;
			if ((den==0)||(den<num))
				cout << "Not valid. Try again." << endl;
			} while ((den==0)||(den<num));
			stk.numShares.initialize (num, den, ok);
			portfolio1.addStock(stk);
			cout << "Your stock has been added." << endl;
			break;

		case 2:
			cout << "Enter the name of the stock to be deleted." << endl;
			cin >> name;
			portfolio1.deleteStock(name);
			cout << "Your stock has been deleted." << endl;
			break;
			
		case 3:
			cout << "Enter the name of the stock to be updated. " << endl;
			cin >> name2;
			portfolio1.findStock(name2, stk2);
			cout << "What do you want to update?" << endl;
			cout << "1. Price per share " << endl;
			cout << "2. Low sell price " << endl;
			cout << "3. High sell price " << endl;
			cout << "4. Number of shares purchased / available. " << endl;
			cout << "5. I'm finished. " << endl;
			do {
			cin >> input2;
			switch (input2)
			{
			case 1:
				cout << "Enter price per share. \n";
				cin >> stk2.buyAt;
				break;
			case 2:
				cout << "Enter Low sell price. \n";
				cin >> stk2.sellLow;
				break;
			case 3:
				cout << "Enter High sell price. \n";
				cin >> stk2.sellHigh;
				break;
			case 4:
				cout << "Enter number of shares purchased. (numerator) " << endl;
				cin >> num2;
				cout << "Enter total number of shares available. (denominator) " << endl;
				cin >> den2;
				stk2.numShares.initialize (num2, den2, ok);
				break;
			case 5:
				portfolio1.updateStock(stk2);
				cout << "Update complete." << endl;
				break;
			default:
				cout << "Not a valid choice. Choose again. \n";
			}
			} while (input2!=5);
			break;
		case 4:
			cout << "Enter name of stock to print. \n";
			do {
			cout << "Enter the name of the stock. \n";
			cin >> name3;
			if (strlen(name3)>nameLength)
				cout << "Too long. Please try again. \n";
			} while (strlen(name3)>nameLength);
			portfolio1.print(name3);
			break;			
		case 5:
			cout << "Goodbye!" << endl;
			portfolio1.printPort();
			break;
		default:
			cout << "Not a valid choice. Choose again. \n";
		}
	}
		while (input!=5);


}

From what I can tell, my add stock method adds the first three stocks I choose to add, and after that the stocks are stored as gibberish. I'd assume the problem is located in that specific method, nothing else should alter that.... so... any help on debugging that one snippet of code would be greatly appreciated.

Also, I realize there's no check for stocks of the same name yet. I wanted to get this fixed before I did it.

After those two minor fixes, I need to expand the program for my lab due monday. Making it used mixed numbers instead of what it currently uses. I'll post that bit below in case anyone has some basic reccomendations, but my main concern is the above issue.

CPP / C++ / C Code:
class mixed : public rational
{		// mixed number class
		// conditions maintained in class:
  	// wh >= 0, denom > 0, sign maintained in numer
	public:
		mixed(); // almost mirrors original constructor
		mixed (int whole, int numerator, int denominator);
			// declares and initializes the rational number.
		void initialize (int whole, int numerator, int denominator, boolean &ok);
			// initializes the rational number.  ok= (denominator > 0)
		int returnWhole ();   // returns the whole number portion of the mixed number
		void reduce ();
		void add (mixed fraction);
    mixed operator+ (mixed fraction);
		mixed operator- (mixed subtrahend);

	protected:
		int wh; // whole number
}; // class mixed

  #2  
Old 08-Oct-2005, 18:57
WaltP's Avatar
WaltP WaltP is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Midwest US
Posts: 3,335
WaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to all

Re: Hitting a logic problem I can't solve


I'd suggest (before Dave does ) add output statements to see what data is being manipulated to see if data at each step is as you expect. A quick look shows nothing obvious except some simplification as shown below.

Here is your add code:
CPP / C++ / C Code:
void portfolioClass::addStock (stockType stock) { //adds "stock" to data alphabetically.
    int count=numActive-1;
    int z=0;
    
    if(numActive>0){
        do{
            if(strcmp (stock.name,data[count].name)== -1){
                data[count+1]=data[count];
                count--;
            }
            else{
                data[count+1]=stock;
                numActive++;
                z=1;
            }
        }while(z!=1);
    }
    if(numActive<=0){
        data[0]=stock;
        numActive++;
    }
}
First thing I did was replace TABs with 4 spaces so the code isn't so wide. I'd recommend using 4 spaces in place of all TABS.

Notice your structure is
CPP / C++ / C Code:
    if (numActive > 0)
    {
        // code
    }
    if (numActive <= 0)
    {
        // code
    }

The second if is redundant. If numActive is not greater than 0 then it must be less than or equal to 0. Alternative structure is
CPP / C++ / C Code:
    if (numActive > 0)
    {
        // code
    }
    else
    {
        // code
    }
__________________

During the election they said Obama could only be elected when pigs fly. Well, we currently have an epidemic of Swine Flu. Coincidence?
  #3  
Old 08-Oct-2005, 20:05
Elsydeon Elsydeon is offline
Junior Member
 
Join Date: Aug 2005
Posts: 45
Elsydeon is on a distinguished road

Re: Hitting a logic problem I can't solve


Actually that was in there because I planned (and just did) add a check for stocks that were trying to be put in twice. That way I could keep that method from doing anything if IBM was entered multiple times to add.

I finally found my logic error. After a trip to the local bar and a beer my brain untangled and now my add stock works fine. Heh. My code didn't take into account that if say the first entry was a greater hex value than the second, then count would send it out of the array boundaries. It's fixed and works fine now.

Now, I just need to add the class mentioned in the first post... and figure out just what on earth we're intended to change about this program.
  #4  
Old 09-Oct-2005, 22:29
Elsydeon Elsydeon is offline
Junior Member
 
Join Date: Aug 2005
Posts: 45
Elsydeon is on a distinguished road

Re: Hitting a logic problem I can't solve


Ok, so.... the lab doesn't make much sense from a "this is a useful change" perspective, it's simply there to teach us to mess with inheritance I think. But, basically we need to add on the ability to convert the stock fractions to mixed numbers. That's mostly implemented here. But, I've got some hangups.

First and foremost.... how do I overload operators to add or subtract mixed numbers? I've looked at examples of how to do it, but I don't understand them. If someone could put it into words for a guy who doesn't know what he's doing at all that'd be helpful.

Second..... if I'm overloading operators for add and subtract, I don't know why there's an add method to include. I guess he wants us to send from main two numbers to add, which then adds the numbers.... but then why no subtract also? Meh..... anyway, I can do what I think I'm supposed to do if I just get my operators overloaded, so..... can anyone explain to me how?

After that I just have to write a rough main that'll let him test it. Shouldn't be too hard.

CPP / C++ / C Code:

#include "rat5Nest.h"
#include <cstring>
#include <string.h>
#include <stdio.h>


const int
	nameLength = 4,
	maxStocks = 50;						// maximum number of stocks

struct stockType {					// data about a stock
 char name[nameLength];			// 3 or 4 letter stock code (ex: IBM)
 float buyAt,								// purchase price per share
	sellLow,									// when it goes below this price, sell?
	sellHigh;									// when it goes above this price, sell?
 rational numShares;				// number of shares held
 // date datePurchased;			// add when date object purchased
}; // stockType

class portfolioClass {
	// holds an array of stockType
	// conditions maintained in object:
	//	 stock ordered by name
	//	 no repetitions
	public:
		portfolioClass();							// constructor
		void addStock (stockType stock);	// adds stock if it does not exist
		void deleteStock (char code[nameLength]);
							// deletes stock with code = name.
		void findStock (char code[nameLength], stockType &stock);
							// returns stock with name = code
		void updateStock (stockType stock);
							// locates and replaces current entry with stock
		bool allOK ();	// returns the value of ok, then resets it to yep
		void print (char code[nameLength]);
		void printPort();
		int howManyStock();					// returns the number of stock in portfolio
	private:
		stockType data[maxStocks];
		int numActive;		// number of active records in data
		bool ok;				// holds yep until an operation fails
		//void locateStock (char code[nameLength], int &spot, bool &exactMatch);
}; // stockType class

class mixed : public rational
{		// mixed number class
		// conditions maintained in class:
  	// wh >= 0, denom > 0, sign maintained in numer
	public:
		mixed(); // almost mirrors original constructor
		mixed (int whole, int numerator, int denominator);
			// declares and initializes the rational number.
		void initialize (int whole, int numerator, int denominator, bool &ok);
			// initializes the rational number.  ok= (denominator > 0)
		int returnWhole ();   // returns the whole number portion of the mixed number
		void reduce ();
		void add (mixed fraction);
    mixed operator+ (mixed fraction);
		mixed operator- (mixed subtrahend);

	protected:
		int wh, n, d; // whole number
}; // class mixed


mixed::mixed(){//initialize
	bool ok=true;
	mixed::initialize(0,0,1,ok);
}

mixed::mixed(int whole, int numerator, int denominator){//Let's initialize some more
	bool ok=true;
	mixed::initialize(whole, numerator, denominator, ok);
}

void mixed::add(mixed fraction){
 
}

void mixed::initialize(int whole, int numerator, int denominator, bool &ok){//One more time now
  wh=whole;
  rational::initialize(numerator, denominator, ok);
}

mixed mixed::operator +(mixed fraction){//Overloads operator so that mixed numbers can be added together
mixed temp1, temp2;
}

mixed mixed::operator -(mixed subtrahend){//Overloads operator so that mixed numbers can be subtracted from each other
mixed temp1, temp2;
}

void mixed::reduce(){//Reduces a pure fraction to a mixed number.
	bool comp=false;
	int tempnum, tempdenom;
	if(rational::returnNumerator()>=rational::returnDenominator()){//Get numerator and denominator
			tempnum=rational::returnNumerator();
			tempdenom=rational::returnDenominator();
			
	}
	do{//Reduce by checking for an oversized numerator and subtracting the denominator if it is, incrementing wh, and repeating until done
		if(tempnum>=tempdenom){
			tempnum=tempnum-tempdenom;
			wh++;
		}
		else{
			comp=true;
		}
	}while(comp=false);
}

int mixed::returnWhole(){//Returns wh
	return(wh);
}



portfolioClass::portfolioClass() // constructor
{	
	numActive=0;
	ok=true;

}

bool portfolioClass::allOK () { //returns true if ok is true and false if ok is false
	if (ok)
		return true;
	else
		return false;
	ok=true;
}

void portfolioClass::updateStock (stockType stock) { //uses "stock" to replace the instance in
													//the portfolio with the matching name.
	int i=0, loc=0;
	bool fin=0;
	do {
		if (!strcmp(stock.name, data[i].name)) {
			fin=1;
			data[i] = stock;
		}
		i++;
	} while ((!fin)&&(i<=numActive));


}

void portfolioClass::addStock (stockType stock) { //adds "stock" to data alphabetically.
	int count=numActive-1;
	int z=0, checker=0;
	
	for(int checking=0;checking<numActive;checking++){//Checks to see if stock is a repeat
		if((strcmp (stock.name,data[checking].name)== 0))
			checker=1;
	}

	if(numActive>0 && checker!=1){//If not a repeat, goes through list and places new stock alphabetically
		do{
			if(strcmp (stock.name,data[count].name)== -1){
					data[count+1]=data[count];
					count--;
				}
			if((strcmp (stock.name,data[count].name)== 1)||(count<0)){
				data[count+1]=stock;
				numActive++;
				z=1;
			}
		}while(z!=1);
	}
	if(numActive<=0 && checker!=1){//If no stock are present, simply puts stock in slot 0
		data[0]=stock;
		numActive++;
	}
}

void portfolioClass::findStock (char code[nameLength], stockType& stk) { //sets stk to the Portfolio
																		//stock with the same name.
	int i=0;
	bool fin=0;
	do {//Searches through portfolio for stock of same name and pulls it
		if (!strcmp(code, data[i].name)) {
			fin=1;
			stk = data[i];
		}
		i++;
	}
		while ((!fin)&&(i<=numActive));
}

void portfolioClass::deleteStock (char code[nameLength]) { //deletes stock in portfolio with 
															//given name.
	stockType stock;
	int i=0;
	bool fin=0;
	do {//Searches for stock to delete
		if (!strcmp(code, data[i].name)) {
			for (int j=i; j<=numActive; j++)
				data[j]=data[j+1];
			fin=1;
			numActive--;
		}
		i++;
		} while ((!fin)&&(i<=numActive));
	if (fin=0)
		cout << "no match found. \n";
}

int portfolioClass::howManyStock () { //returns the number of active stock
	return numActive;
}
void portfolioClass::print (char code[nameLength]) { //Simply prints stock matching code
		int i=0;
	bool fin=0;
	do {
		if (!strcmp(code, data[i].name)) {
			i--;
			fin=1;
		}
		i++;
		} while ((!fin)&&(i<=numActive));
	if (fin=0)
		cout << "no match found. \n";
		cout << endl<<"Name: "<<data[i].name << endl;
		cout << "Buy At: "<<data[i].buyAt << endl;
		cout << "Sell Low: "<<data[i].sellLow << endl;
		cout << "Sell High: "<<data[i].sellHigh << endl;
		cout << "Owned/Total: "<<(data[i].numShares.returnNumerator ()) << "/" << (data[i].numShares.returnDenominator ()) << endl;
}

void portfolioClass::printPort(){
	for(int g=0;g<numActive;g++){
		cout << endl<<"Name: "<<data[g].name << endl;
		cout << "Buy At: "<<data[g].buyAt << endl;
		cout << "Sell Low: "<<data[g].sellLow << endl;
		cout << "Sell High: "<<data[g].sellHigh << endl;
		cout << "Owned/Total: "<<(data[g].numShares.returnNumerator ()) << "/" << (data[g].numShares.returnDenominator ()) << endl;
	}
}
 
 

Recent GIDBlogToyota - 2009 May Promotion by Nihal

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Graphic problem in Unreal Tournament 2004 zerox Computer Software Forum - Games 10 09-Oct-2005 13:31
a significant problem after installing Xp mohammad Computer Software Forum - Windows 10 09-Aug-2005 08:03
String problem vaha C Programming Language 3 24-May-2005 19:21
Please help to solve me a problem with multiline texrbox and checkbox mithila MS Visual C++ / MFC Forum 0 08-Sep-2004 23:08
logic problem? ozzytx C++ Forum 3 09-Jul-2004 03:23

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 14:43.


vBulletin, Copyright © 2000 - 2009, Jelsoft Enterprises Ltd.