Reputation: 13
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.
Now i'm not asking for the answer but, i'm asking how do i approach it. simply because i'm not sure how to address the question like how to code it. I have understand the first paragraph of the question respectively. here is my snippet of code. now im just stuck on how to compute it. i just need a bit of guidance. Thanks! the code i have so far, accesses the array I have of 12 elements and assigns them random numbers of dollars and cents respectively.
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <cmath>
using namespace std;
struct Money
{
int dollars,cents;
};
int main()
{
Money monthlySales[12], yearlySales;
for (int i = 0; i < 12; i++)
{
monthlySales[i].cents =rand()%99;
monthlySales[i].dollars =rand();
}
return 0;
}
Upvotes: 0
Views: 2338
Reputation: 1
This works too!
float dollar = 0;
float cent = 0;
for (int i = 0; i < 12; i++) {
dollar += monthlySales[i].dollars;
cent += monthlySales[i].cents;
do {
if (cent > 100 ) {
dollar += 1;
cent -= 100;
}
}while (cent > 100);
}
yearlySales.dollars = dollar;
yearlySales.cents = cent;
Upvotes: 0
Reputation: 205
//to compute Sum
for (int i = 0; i < 12; i++)
{
yearlySales.cents +=monthlySales[i].cents;//keeps adding yearlySales cents for each month
yearlySales.dollars +=monthlySales[i].dollars;//keeps adding yearlySales dollars
}
//if cents 100 convert it into dollars eg:720cents is convereted to 7$ 20 cents and 7 dollars is added to yearly dollars
if(yearlySales.cents > =100)
{
yearlySales.dollars+=yearlySales.cents/100;
yearlySales.cents=yearlySales.cents%100;
}
Upvotes: 1
Reputation: 64702
Write the necessary code that traverses the monthlySalesarray 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.
Money monthlySales[12], yearlySales;
yearlySales.cents = 0;
yearlySales.dollars = 0;
for (int i = 0; i < 12; i++)
{
yearlySales.cents += monthlySales[i].cents; // Add up the cents
yearlySales.dollars += monthlySales[i].dollars; // Add up the dollars
yearlySales.dollars += yearlySales.cents / 100; // If cents > 100, increase dollars appropriately.
yearlySales.cents = yearlySales.cents % 100; // If cents > 100, set it to the remainder.
}
Upvotes: 3