Value not being increased after addition statement? - c++

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.

Related

Why is my parallel array displaying random values?

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.

Abstract Data Type Pass as a parameter

Hey so I'm trying to pass a hash table as a parameter in c++, when I call the function that I am trying to run i get an error message that i do not understand.
So this is the function:
string getRandomKey(int tableNumber, int tableSize, HashTable<string>* table, int random){
random *= rand() % tableSize + 1;
string randKey = to_string(tableNumber) + to_string(random);
if((table->find(randKey)) == true){
cout << "Key: " << randKey << " found ";
return randKey;
}
return "";
}
This is by no means the final version I'm just trying to test it. Some context is that I have a couple of hash tables, and a separate integer variable that has the number of elements that i have predetermined. The keys are set to be one of the random numbers.
Anyway so here is where I call the function:
table1->print(getRandomkey(1, sizes[2], table1*, 1));
And I get this error:
error: expected expression
table1->print(getRandomKey(1, sizes[2], table1*, 1));
^
1 error generated.
So, I'm not sure what I need to change or if I messed something up somewhere else. Thanks for any help you guys can give!
It appears that table1 is a pointer to a HashTable so when you
make the call to getRandomKey the term table1* should just be table1.
table1->print(getRandomkey(1, sizes[2], table1, 1));

C++ Class Variable not updating

I'm trying to code a counter for a class I made in c++.
I'm passing an amount of time, deltaT, to a method of the Wake class, which does simply adds it onto the value already stored by a variable in the class. The code is:
void checkPlayerWakes(int deltaT){
for(size_t i = 0; i < game.getPlayer().getWakes().size(); i++){
Wake& w = game.getPlayer().getWakes().at(i);
w.age(deltaT);
}
}
However, the timer which is meant to be increasing, is remaining at 0.
The code to change the timer is:
void Wake::age(int millis) {
cout << "Updating : " << currentLife;
this->currentLife += millis;
setAlpha(((double)currentLife)/((double)lifeTime));
cout << " " << currentLife << endl;
}
E.g.
first current life: 0
second current life: 16
I know that if I were to use
Wake w = something
w.age(deltaT)
it wouldn't work because "w" would just be a copy of the object. However, that's clearly NOT my problem here? Also game.getPlayer() also returns a reference, a PLAYERSHIP&.
Last time I had a similar problem, it was solved by calling and returning references instead of just the ClassName. Am I still doing something wrong?
getWakes() needs also to return a reference, and should return vector& as opposed to vector.
I'm adding this here to make sure that this question is marked as answered.

adding an array of class objects into one master class object

for a project I had to create a class that had variables for feet and inches, and had a method to add these variables together from object 1 and object 2, then object 3, 4, and so on.
CDistance CDistance::add(const CDistance& yourDist) const
{
CDistance total;
total.feet += yourDist.feet;
total.inches += yourDist.inches;
/*if (total.inches > 12)
{
total.feet += (total.inches / 12);
total.inches = total.inches % 12;
}*/
return total;
}
that's the method I have for adding, and here is a function in the main source file, where I process each class
void printAndAdd(const CDistance distList[], int size)
{
CDistance new_total;
new_total = distList[0].add(distList[1].add(distList[2].add(distList[3].add(distList[4]))));
new_total.printDist();
}
And here is the method I use to print out the data on screen
void CDistance::printDist() const
{
cout << "Feet: " << this->feet << "\n\n";
cout << "Inches: " << this->inches << "\n\n";
}
I thought about using a for loop, for that 2nd line, but I'm having a bit of a problem. Whenever I print the data out, it's 0. As if the add function isn't working, which I'm not quite sure I even understand what I did. From what I think I'm doing, it's creating a new obejct, adding the variables from the referenced to object to the created object, that commented out section is a section I just took out for now and will add later, and then it returns the object. When I call the function in my main source file it would set the object new_total equal to the sum of object 0, 1, 2, 3, and 4. Am I close, or way off to what's actually happening? I should also explain that I've only been programming for about a year, it's really intriguing to me, but naturally difficult at times, and I'm still trying to grasp my hands around the idea of classes in c++.
The problem is that you never use the instance variables when adding. Instead you always start from a freshly minted object. Try this:
CDistance CDistance::add(const CDistance& yourDist) const
{
CDistance total(*this);
total.feet += yourDist.feet;
total.inches += yourDist.inches;
this->feet += yourDist.feet;
this->inches += yourDist.inches;
return total;
}
I've done some playing with your code and it looks like this line should is incorrect:
CDistance total;
The value of total is never initialized and is therefore always going to be whatever your default constructor has defined it to be (probably 0/0). Thus, the result of that call will always end up whatever was passed to the input. I think you meant to do this:
CDistance total = *this;
That will copy the current values for feet an inches into the temp and then the following lines will add the input. Passing through the chain of calls like you do should now concatenate the additions as expected.

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