0

给定一个类型Money,它是具有两个int 字段的结构化类型,美元和美分。假设一个以monthlySales12 个元素命名的数组,每种类型 Money都已声明和初始化。

假设还声明了一个Money-variable 。yearlySales编写遍历monthlySales-array 的必要代码并将其全部相加并将结果总数存储在yearlySales. 确保yearlySales以有效值结束,即小于 100 的美分值。

现在我不是在问答案,而是在问我该如何解决。仅仅是因为我不确定如何解决诸如如何编码之类的问题。我已经分别理解了问题的第一段。这是我的代码片段。现在我只是坚持如何计算它。我只需要一点指导。谢谢!到目前为止,我的代码访问了我拥有的 12 个元素的数组,并分别为它们分配了美元和美分的随机数。

#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;
    }
4

3 回答 3

3

编写遍历monthlySalesarray 的必要代码,并将其全部相加,并将结果总数存储在yearlySales 中。请务必确保 yearlySales 以有效值结束,即小于 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.
}
于 2013-10-02T15:27:43.990 回答
1
     //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;
    }
于 2013-10-02T15:30:30.087 回答
0

这也有效!

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;
于 2016-11-06T23:37:28.993 回答