Why is my parallel array displaying random values? - c++

I am supposed to use a parallel array to show how much a cup of coffee is based on what add-in is added. The original cup of coffee is 2 dollars. I am mostly confused with how to output the correct results. Currently, it will output saying "Order total is2". What am I missing?
// JumpinJava.cpp - This program looks up and prints the names and prices of coffee orders.
// Input: Interactive
// Output: Name and price of coffee orders or error message if add-in is not found
#include <iostream>
#include <string>
using namespace std;
int main()
{
// Declare variables.
string addIn; // Add-in ordered
const int NUM_ITEMS = 5; // Named constant
// Initialized array of add-ins
string addIns[] = {"Cream", "Cinnamon", "Chocolate", "Amaretto", "Whiskey"};
// Initialized array of add-in prices
double addInPrices[] = {.89, .25, .59, 1.50, 1.75};
bool foundIt = false; // Flag variable
int x; // Loop control variable
double orderTotal = 2.00; // All orders start with a 2.00 charge
// Get user input
cout << "Enter coffee add-in or XXX to quit: ";
cin >> addIn;
// Write the rest of the program here.
for(int i = 0; i < NUM_ITEMS; i++){
if (addIns[i] == (addIn))
foundIt = true;
if (foundIt)
{
x = orderTotal + addInPrices[i];
cout << "Order Total is" << x << endl;
}
else cout <<"Sorry, we do not carry that."<< endl;
}
return 0;
} // End of main()

In this line:
x = orderTotal + addInPrices[i];
you are setting x (an int value) to something like 2.00 + 0.25, right? Your compiler is likely warning you about a possible loss of precision here. An integer value can only contain whole numbers: 1, 2, 3, etc. If you try to set it to a floating point number like 2.25, it will be truncated (the decimal points chopped off) leaving only the integer part. So the result of x = 2.25 will be the value 2 in x, which is consistent with your output.
In your assignment template, your instructor has written this comment next to the declaration of x:
int x; // Loop control variable
It seems clear to me that the intent was for x to be what you put in the for loop, i.e. the variable controlling how many loops happen and when it ends. You are choosing to create a new variable i instead. This would also explain why x is not initialized to anything - the initialization would happen in the for-loop if you did it the intended way.
Try this: Instead of using x to store the new price, simply add the add-in price to orderTotal, so that it's always up-to-date and has the correct value. This way you do not need to use x for this at all, and can use it in the for-loop instead. You would then be printing orderTotal instead of x in your output.

Related

My program doesn't end

I'm new too c++ and I had to design a program that determines the first four triangular square numbers and the output is exactly how I want it to be, but it wont quit after its printed the first four. I can't figure out what it could be. I can't CTRL C because I will get points taken off. What is the issue here?
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
//Prints name line
cout<<"*********** BY: ********"<<endl;
//Initializing
const int HOW_MANY=4;
int num=1;
int tsn=0;
int z=1;
int x=0;
//How many TSN it will find and be printed
while (x<=HOW_MANY)
{
//
int sum=0;
for (int y=0;y<512;y++)
{
sum+=y;
tsn=pow(num,2);
//Tests if the numbers are TSN
if ((sum==tsn) || (num+1)/sqrt(num)==sqrt(num))
{
//Prints 1-HOW_MANY TSN and what they are
cout<<"Square Triangular Number "<< z <<" is: "<< tsn <<endl;
z++;
x++;
}
}
num++;
}
return 0;
}
If x = 0 then instead of while (x<=HOW_MANY) you need write while (x<HOW_MANY).
x begins at 0. Every time you find and print a number it gets incremented. You'll continue this, so long as x<=HOW_MANY.
You say your program finds 4 numbers but keeps running. After 4 hits, x will be 4. Is 4 <= 4? The answer is yes, so your program keeps running.
Either change the condition to x < HOW_MANY, or initialize x to 1.
EDIT
Did a little leg work, it turns out the sum of all the numbers in the range [1,512] is 131328. The 5th square triangle number is 1413721.
This means after you find the fourth triangle number, you will never sum high enough to find the next one. This will result in the infinite loop you're seeing.
The answer above is still the correct fix, but this is the reason you end up with an infinite loop.
for should be used for iteration and while should be used for condition testing.
The problem, as has been noted, is that your x condition variable is never being incremented to get you out of the outer loop. That's a logic error that can be avoided by using the appropriate control structure for the job.

Displaying content with a for loop

I'm trying to write a program that randomly selects three items from an array that contains five different fruits or vegetables and then display this randomly selected content to the user. Now I'm having trouble understanding why my output is not consistent because sometimes when I run it I'll get something like this:
This bundle contains the following:
Broccoli
With the first two items missing and sometimes I'll get this:
This bundle contains the following:
Tomato
Tomato
Tomato
This is the portion of the code I'm currently having trouble with:
void BoxOfProduce::output() {
cout << "This bundle contains the following: " << endl;
// Use this so it will be truly random
srand(time(0));
for (int f = 0; f < 3; f++) {
// Here were making the random number
int boxee = rand() % 5;
// Adding the content to the box
Box[f] = Box[boxee];
// Now were calling on the function to display the content
displayWord(boxee);
} // End of for loop
} // End of output()
void BoxOfProduce::displayWord(int boxee) {
cout << Box[boxee] << endl;
}
int main() {
BoxOfProduce b1;
b1.input();
b1.output();
Can someone help me understand why i'm getting this output? Thanks!
Don't do it like you are doing it :)
Like #John3136 pointed out, you are messing up your Box variable..
void BoxOfProduce::output()
{
srand(time(NULL)); //keep in mind that this is NOT entirely random!
int boxee = rand() % 5;
int i = 0;
while(i<5)
{
boxee = rand() % 5;
cout<<Box[boxee]<<endl; //this line might be wrong, my point is to print element of your array with boxee index
i++;
}
}
Box[f] = Box[boxee]; is changing the contents of the "Box" you are picking things out of. If the first random number is 3, item 3 gets copied to item 0, so now you have twice as much chance of getting that item the next time through the loop...
You are overwriting the elements of your array with randomly selected item.
Box[f] = Box[boxee];
For eg: If boxee=1 and f=0, it will overwrite element at index 0 with 1, while at same time element at index 1 is same leaving two copies of same item.
Use :std:random_shuffle instead.

Using my class member functions practically

I'm trying to make a program that does input/output in the following way, notice that I HAVE NOT finished all of the functions yet. I just need some tips on how to get started because I'm completely stumped on what to do...ANY hints/help would be so appreciated.
Input follows this:
Add Alice
Add Bob
Update Alice laptop 6000 2
Output Alice
Update Bob deskTop 18000 4
Update Bob tabLet 4600 3
Output Bob
Add Charlie
OUTPUT FOR THIS INPUT:
Alice is seller 1.
Bob is seller 2.
Alice sold 2 laptop computers for 6000 Dollars.
Alice: $6000; sold 2 LapTops, 0 DeskTops and 0 Tablets.
Bob sold 4 desktop computers for 18000 Dollars.
Bob sold 3 tablet computers for 4600 Dollars.
Bob: $22600; sold 0 LapTops, 4 DeskTops and 3 Tablets.
Charlie is seller 3.
I really have no idea where to start off now... I need to be able to input the command followed by arguments for the member function parameters...but really have no clue how to incorporate this... this is my second month in C++, so note that I really don't know any advanced things. I have knowledge up to classes....
Main question is just how to use these practically...
Other important info:::: 1. Add – Add command. Add a seller with the given name (Sellername) to the end of the list if a seller with that name doesn't already exist and the list isn't full. The name will be a contiguous sequence of non-white-space characters. Your program doesn't need to check this. See sample outputs.
Output – Output command. Output the total value of computers sold and the total number of each type of computer sold for that seller. If the seller doesn't exist, print an appropriate message. See sample outputs.
Update – Update command. Update the seller with the given sales and the appropriate number of computers. For this command: Sellername designates the name of the sales person; typeOfComputer designates either laptop, desktop or tablet; total-Dollars designates the amount in dollars that was sold; number-of-Computers-Sold designates the quantity of computers of this type that were sold. Your program should convert the typeOfComputer parameter to lower case, as the input will use a mixed case designation. [Hint, include , use function
char tolower(char c); // if c is upper case, returns it in lower case
If the seller doesn't exist, print an appropriate message (and read and discard the data). See sample outputs.
Quit – Quit command. Print out the list of people who sold enough to win the fabulous vacation.
#include <iostream>
#include <cctype>
#include <string>
#include "conio.h"
using namespace std;
const int MAX_SELLERS = 5;
const int NOT_FOUND = -1;
const float GOAL_IN_DOLLARS = 35000.0f;
const int GOAL_IN_COMPUTERS = 12;
class Seller
{
private:
float salestotal; // run total of sales in dollars
int lapTopSold; // running total of lap top computers sold
int deskTopSold; // running total of desk top computers sold
int tabletSold; // running total of tablet computers sold
string name; // name of the seller
public:
// default constructor
Seller()
{
name = "";
salestotal = 0.0;
lapTopSold = 0;
deskTopSold = 0;
tabletSold = 0;
}
// parameterized constructor and member functions
// Constructor:
// Initializes the Seller's name to newname.
// Initializes the Seller's salestotal to 0 and all integer fields to 0.
// Params: in
Seller ( string newname );
// Returns true if the seller's name is the same as nameToSearch;
// false otherwise.
// Params: in
bool SellerHasName ( string nameToSearch );
// Returns true if the seller sold GOAL_IN_COMPUTERS computers
// or GOAL_IN_DOLLARS sales or more.
// Params: NONE
bool WinsPrize ( );
// Adds the money and number of computers to the seller's accumulated
// sales total and number of computers sold based on the computer type.
// That is, if the computer type is “DESKTOP” then the desktop field is
// updated by numComputers, if the computer type is “LAPTOP” then the
// laptop field is updated by numComputers, if the computer type is
// “TABLET” then the tablet fields is updated by numComputers.
// Params: in, in, in
void UpdateSales ( float totalDollars, int numComputers,
string computerType );
// Print the salesperson's name, sales total, and number of
// computers sold.
// Params: NONE
void PrintSales ( );
};
Seller::Seller(string newname)
{
name = newname;
salestotal = 0.0;
lapTopSold = 0;
deskTopSold = 0;
tabletSold = 0;
}
bool Seller::SellerHasName ( string nameToSearch )
{
if(name == nameToSearch)
return true;
else
return false;
}
bool Seller::WinsPrize ( )
{
if(salestotal >= GOAL_IN_DOLLARS || (lapTopSold + deskTopSold +
tabletSold) >= GOAL_IN_COMPUTERS)
return true;
else
return false;
}
void Seller::UpdateSales( float totalDollars, int numComputers,
string computerType )
{
salestotal += totalDollars;
if(computerType == "DESKTOP")
deskTopSold += numComputers;
else if(computerType == "LAPTOP")
lapTopSold += numComputers;
else if(computerType == "TABLET")
tabletSold += numComputers;
}
void Seller::PrintSales ()
{
cout << name << " " << salestotal << "; sold " << lapTopSold <<
"LapTops, " << deskTopSold << " DeskTops, " << "and " <<
tabletSold << " Tablets." << endl;
}
class SellerList
{
private:
int num; // current number of salespeople in the list
Seller salespeople[MAX_SELLERS];
public:
// default constructor to make an empty list
SellerList()
{
num = 0;
}
// member functions
// If a salesperson with thisname is in the SellerList, this
// function returns the associated index; otherwise, return NOT_FOUND.
// Params: in
int Find ( string thisName );
void Add(Seller sellerName);
void Output(Seller sellerName);
};
int SellerList::Find(string thisName)
{
for(int i = 0; i < MAX_SELLERS; i++)
if(salespeople[i].SellerHasName(thisName))
return i;
return NOT_FOUND;
}
// Add a salesperson to the salespeople list IF the list is not full
// and if the list doesn't already contain the same name.
void SellerList::Add(Seller sellerName)
{
Seller(sellerName);
num++;
}
// Output the total value of computers sold and the total number of each
// type of computer sold for that seller. If the seller does not
// exist, print an appropriate message
void SellerList::Output(Seller sellerName)
{
}
int main()
{
return 0;
}
Assuming your Seller implementation is correct and comprehensive (I didn't check it) all you need to do is parse input. In order to parse input, you should read it line by line, interpreting each line as some sort of a command. This command consists of a command name itself along with its arguments (if any).
There are several approaches:
First one:
While end of file isn't reached:
Read a line (string from the current position up to \n symbol)
Split it by spaces. First element of the result is command, rest are arguments. You may need to convert it to appropriate type before executing Seller's method.
Second one:
While end of file isn't reached:
Read a word (from current position up to whitespace symbol).
Now you know the command. If you know the command, you know what arguments should be passed. You can extract them from input right there or delegate it to some other function / method (you pass a reference to input stream to that function and work with that reference)
Take a look at documentation on <iostream> in order to see function's and method's names as well as some examples.

C+ program involving functions...Please help me

I am having a hard time with two functions. Here are the project instructions:
Assignment:
Write a program which keeps track of the number of roaches in two adjacent houses for a number of weeks. The count of the roaches in the houses will be determined by the following:
The initial count of roaches for each house is a random number between 10 and 100.
Each week, the number of roaches increases by 30%.
The two houses share a wall, through which the roaches may migrate from one to the other. In a given week, if one house has more roaches than the other, roaches from the house with the higher population migrate to the house with the lower population. Specifically, 30% of the difference (rounded down) in population migrates.
Every four weeks, one of the houses is visited by an exterminator, resulting in a 90% reduction (rounded down) in the number of roaches in that house.
Here's my code:
#include <iostream>
#include <cmath>
using namespace std;
int house, increase, roaches, moreRoaches, fewerRoaches, filthyBeasts, change; // My variables for my four functions
int initialCount(int house);
int weeklyIncrease(int increase);
double roachesMigration(int moreRoaches, int fewerRoaches, int change);
int exterminationTime (int filthyBeasts);
// My four function prototypes
int main()
{
int houseA, houseB;
houseA = initialCount(houseA); //Initializing the initial count of House A.
houseB = initialCount(houseB); //Initializing the initial count of House B.
int week = 0;
for (week = 0; week < 11; week++) // My for loop iterating up to 11 weeks.
{
houseA = weeklyIncrease(houseA);
houseB = weeklyIncrease(houseB);
cout << "For week " << week << ", the total number of roaches in House A is " << houseA << endl;
cout << "For week " << week << ", the total number of roaches in House B is " << houseB << endl;
if((houseA > houseB)) // Migration option 1
{
roachesMigration(moreRoaches, fewerRoaches, change);
}
else if((houseB > houseA)) // Migration option 2
{
roachesMigration(moreRoaches, fewerRoaches, change);
}
if ((week + 1) % 4 == 0) // It's extermination time!
{
if ((rand() % 2) == 0) // Get a random number between 0 and 1.
{
houseB = exterminationTime(houseB);
}
else
{
houseA = exterminationTime(houseA);
}
}
}
return 0;
}
int initialCount(int house) // Initializing both houses to random numbers between 10 and 100.
{
int num;
num = (rand() % 91) + 10;
return num;
}
int weeklyIncrease(int increaseHouses) // Increasing the roaches in both houses by 30% weekly.
{
int increase = 0;
increase = (increaseHouses * .3) + increaseHouses;
return increase;
}
double roachesMigration(int moreRoaches, int fewerRoaches, int change)
{
more -= change;
fewer += change;
change = ((more - fewer) * .3);
return change;
}
int exterminationTime(int filthyBeasts) // Getting rid of the filthy little beasts!
{
filthyBeasts = (filthyBeasts * .1);
return filthyBeasts;
}
The issues are with the migration and extermination functions. My code runs fine, but at weeks 4 and 8, the randomly selected house should get exterminated, and the number of roaches in that house should be 90% less than the previous week. What do you guys think I should do to correct these issues? I really need all the help I can get!
Regarding this line:
roachesMigration(change);
change is not declared in your main function, hence the error. Also, roachesMigration function expects 3 parameters and not 1.
The variable change is not a global variable, but appears inside main (so it has no meaning inside main).
Your roachesMigration fonction is declared with three formal arguments (without default values), but you use it with one actual argument.
Ask your compiler to give you all the warnings and to produce debugging information (g++ -Wall -g on Linux). Improve the code till you get no warnings.
Learn to use a debugger (e.g. gdb on Linux).
Have fun.
Depending on the instructor, you will get zero marks for this code, even if you can get it to work perfectly! This is because you have not used any object orientated design in building your code. In C++, that means classes.
What sort of object do you need for this problem. A house!
What sort of attribute should your house have? Roaches!
So something like this:
class cHouse
{
int MyRoachCount;
...
};
If you start fresh, like this, you will find things start to fall neatly into place.
One possible way to handle the migration is like this pseudocode:
// compute size of migration
count = migration(houseA, houseB)
if (houseA < houseB)
add count to houseA
subtract count from houseB
else
add count to houseB
subtract count from houseA

Value not being increased after addition statement?

I have two functions where I'm adding random numbers to the total value.
The problem is that every time I call the function and print the total, it does not add. If it generates 2 it will say the total is 2. After that if I call it again and it generates 5, it says the total is 5, and doesn't add (it should be 7 if this happened.)
Everything looks fine here...
int human(int humanscore)
{
int diceRoll= rand() % 7;
cout << "player rolled: ";
humanscore+= diceRoll;
cout << diceRoll;
cout << "human score is: " << humanscore;
}
int computer(int compscore)
{
int diceRoll= rand() % 7;
cout << "computer rolled: ";
compscore+= diceRoll;
cout << diceRoll;
cout << "computer score is: " << compscore;
}
You are modifying the value of the internal copy of the argument passed to the functions. If you want the change to be done on the external variable, change your function definitions to take references instead: int& score.
Also note that rand() % 7 will give you a value in the range [0, 6]. A dice has values in the range [1, 6], you should use 1 + rand() % 6 instead.
* Update: *
This can be done with C++ references:
int computer(int& compscore)
{
...
compscore += diceRoll;
...
}
int var = 0;
computer( var );
For this declaration, the function takes the actual variable var as an argument, and changes done to compscore within the function are reflected in the variable var as compscore and var for that particular invocation are just aliases to the same variable.
In C the same effect is achieved with pointers:
int computer(int* compscore)
{
...
*compscore += diceRoll;
...
}
int var = 0;
computer( &var );
This invocation of the function gives it the address of the variable which should be changed. For general use, you can assume that the first implementation using references will automatically generate a solution by the compiler similar to this last snippet.
You're couting the diceRoll here, so it's only ever going to print the current roll as opposed to the total.
Assuming you're correctly printing the dice roll, you also need to write return humanscore; and return compscore; at the end of those functions to pass back to the new result.
You are passing your parameters by value. This means that any changes to them are thrown away when the function is done. If you want your scores to persist you have a few choices. You could pass the parameters by reference, which in C++ could be done by passing a pointer to the score. You could make your function return the new score, and then pass the returned value to the function the next time you call it. You would also have the significantly less desirable solution of using global variables.