C++ programming question. Given the following definition for the class Money: cl
ID: 3776201 • Letter: C
Question
C++ programming question.
Given the following definition for the class Money: class Monty {private: int dollars; int cents; public: void setValue(int d, int c); void addValue(int d, int c);}; void Money::setValue(int d, int c) {dollars = d; cents = c;}; From the 4 options below, select the correct addValue function definition such that each time a cent amount is added, the total dollar amount is properly updated once we go over 99 cents. That is, the number of cents after the addition should never exceed 99 and if exceeded it should add a unit to the dollar amount. void Money::addValue(int d, int c) {dollars = dollars + d; cents = cents + c; void Money::addValue(int d, int c) {dollars = dollars + d; cents = cents + c; if (cents > 99) {dollars = dollars + (cents/100);} cents = cents % 100;} void Money::addValue(int d, int c) {dollars = dollars + d; cents = cents + c; if (cents > 99) {dollars = dollars + (cents/100); cents = cents/100;}} void Money::addValue(int d, int c) {dollars = dollars + d; cents = cents + c; if (cents > 99) {dollars = dollars + (cents % 100); cents = cents/100;}}Explanation / Answer
Answer is b.
How?
*First let us write the function declaration
void Money::addValue(int d, int c){
}
*Now we add `d` to `dollars` and `c` to `cents`
void Money::addValue(int d, int c){
dollars=dollars+d;
cents=cents+c;
}
*Now we compare if cents is greater than 99. for example if we get cents=121 then that means we have 1 dollar and 21 cents. so we write the function accordingly.
void Money::addValue(int d, int c){
dollars=dollars+d;
cents=cents+c;
if(cents>99){
dollars=dollars+(cents/100)
}
}
Here for 121 we calculate 121/100=1 and then add it to `dollars` variable.
*Now we calculate the remaining cents after adding to the dollar using `%`(percentile) which gives us the remainder.
121%100=21 cents
void Money::addValue(int d, int c){
dollars=dollars+d;
cents=cents+c;
if(cents>99){
dollars=dollars+(cents/100);
}
cents=cents%100;
}
and Hence the answer is `b`
Example:
*You have
dollars=1
cents=95
*You have to add
d=2(dollars)
c=36(cents)
*then according to our program it will be
dollars=1+2=3
cents=95+36=131
131>99
dollars= 3+(131/100)=3+1=4
cents=131%100=31
So the answer is 4 dollar 31 cents.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.