I am totally new to c++ and thought it would be good practice to write a program which solved a given liter puzzle (you have 2 containers with capacities of 3 and 5 liters, can you obtain 4 liters? etc.)
I wrote a class for a given container and a function which was intended to 'pour' the contents of one container into another. The function doesn't change the value of the contents of any object however, despite the entire class being public. I'm not sure what I'm doing wrong.
Here is my code:
#include <iostream>
using namespace std;
class Container {
public:
int quantity; //quantity of water in container
int size; //max amt of water
};
void pour(Container a, Container b) {
int differential = b.size - b.quantity;
if (a.quantity <= differential) {
b.quantity = a.quantity + b.quantity;
a.quantity = 0;
}
else if (a.quantity > differential) {
b.quantity = b.quantity - differential;
a.quantity = a.quantity - differential;
}
};
int main() {
Container bottle1;
bottle1.quantity = 5;
bottle1.size = 6;
Container bottle2;
bottle2.quantity = 0;
bottle2.size = 2;
pour(bottle2, bottle1);
cout << bottle1.quantity << ", " << bottle2.quantity << endl;
return 0;
}
I'm sure my mistake is obvious but I can't find an answer anywhere. Any help would be greatly appreciated.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…