Comp Sci Debugging a Program to Add Up Monthly Sales

  • Thread starter Thread starter sandy.bridge
  • Start date Start date
  • Tags Tags
    Debugging Program
AI Thread Summary
The discussion revolves around debugging a program designed to sum monthly sales represented by a structured type called Money, which includes dollars and cents. The initial code correctly accumulates the values but fails to handle cases where the cents exceed 100 properly. A suggested solution involves adjusting the yearlySales by using division and modulus operations to ensure cents remain valid. The user acknowledges a misunderstanding regarding the accumulation of cents and appreciates the clarification. Ultimately, the focus is on ensuring that the final value of cents in yearlySales is less than 100.
sandy.bridge
Messages
797
Reaction score
1

Homework Statement


This question is rather easy. It is compiled online with CodeLab. For some reason my program executes perfectly except for one of the trials. Here is the question:

Given a type Money that is a structured type with two int fields, dollars and cents. Assume that an array named monthlySales with 12 elements, each of type Money has been declared and initialized.

Assume that a Money variable yearlySales has also been declared. Write the necessary code that traverses the monthlySales array and adds it all up and stores the resulting total in yearlySales. Be sure make sure that yearlySales ends up with a valid value, i.e. a value of cents that is less than 100.



The Attempt at a Solution


My solution:
PHP:
int j = 0; 
yearlySales.cents = 0; yearlySales.dollars = 0;
while (j < 12)
{

yearlySales.cents += monthlySales[j].cents;
yearlySales.dollars += monthlySales[j].dollars;
if(yearlySales.cents >= 100){yearlySales.dollars++; yearlySales.cents -= 100;}

j++;
}

Can anyone see what is not correct about this code?
 
Physics news on Phys.org
yearlySales.cents -= 100
 
Hey phinds! I suppose that makes sense! I didn't really take into consideration if they gave, let's say, 200 cents. Thanks!

PHP:
int j = 0; 
yearlySales.cents = 0; yearlySales.dollars = 0;
while (j < 12)
{

yearlySales.cents += monthlySales[j].cents;
yearlySales.dollars += monthlySales[j].dollars;
if(yearlySales.cents >= 100){yearlySales.dollars += yearlySales.cents/100; yearlySales.cents = yearlySales.cents%100;}

j++;
}
 
Last edited:
sandy.bridge said:
Hey phinds! I suppose that makes sense! I didn't really take into consideration if they gave, let's say, 200 cents. Thanks!

No, you are missing the point.

EDIT: OOPS ... *I* am the one making a mistake. I read "+=" as "=", and you are correct, the only problem I can see would be if a single entry had over 100 cents, which really wouldn't make sense (or wouldn't make proper cents :smile:)
 
Last edited:

Similar threads

Back
Top