0

好吧,所以我有一个任务,我完全被难住了。到目前为止,我的代码如下

#include<iostream>
#include<cstdlib>
#include<fstream>
#include<sstream>

using namespace std;

const int SIZE = 12;

struct Division
{
      char divName[SIZE]; // Division name
      double sales[4]; // Quarterly sales stored as an array
};



int main()
{
       void Intro();
       Division CreateCorporateFile();
       Division DisplayCorporateSales();

       Intro();
       CreateCorporateFile();
       DisplayCorporateSales();


       system("PAUSE");
       return 0;
}

void Intro()
{
     cout<<"This program will prompt you to enter in quarterly sales for "
           "four different\ndivisions of a company.\n\n";
}


Division CreateCorporateFile()
{
     Division div;
     int x = 0;
     //for(int x = 0; x < 4; x++)
 do {
          int quarter = 1;
          cout << "Enter the name of the division: ";
          cin >> div.divName;
          for(int i = 0; i < 4; i++)
          {
              cout << "Enter in the sales for quarter "<< quarter <<": ";
               cin >> div.sales[i];
               if(div.sales[i] > 0)
               {
                    quarter++;
               }
               else
               {
                    cout << "Sales are not allowed to be negative.\n";
               }
          }
          x++;
     } while(x < 4);

     return div;
}


Division DisplayCorporateSales()
{
         Division test;

         Division CreateCorporateFile();

         test = CreateCorporateFile();

         for(int i = 0; i < 4; i++)
         {
             cout << "Here are the quarterly sales for " << test.divName
              << ": ";
             for(int i = 0, quarter = 1; i < 4; ++i, ++quarter)
             {
                  cout << "Quarter "<< quarter << " sales: $"<< test.sales[i]
                   <<"\n";
             }
         }

         return test;

}

我遇到的一个问题是它最终提示 8 个分区(应该只执行 4 次),另一个是它最终只显示第 8 个分区的数据。所以有人知道我哪里出错了吗?因为我没有,而且我已经为此工作了几个小时,所以我可能忽略了明显的细节。

4

2 回答 2

1

您只显示最终数据的原因DivisionCreateCorporateFile只返回一个Division实例。每个 do-while 循环都会覆盖前一个循环的内容。

对此的一种解决方案是返回一个数组

std::vector<Division> CreateCorporateFile()
{
    std::vector<Division> divArray;
    Division div;
    int x = 0;
    do {
        ...
        divArray.push_back(div);
        x++;
    } while(x < 4);

    return divArray;
}

void DisplayCorporateSales()
{
    std::vector<Division> divisions = CreateCorporateFile();
    for (size_t i=0; i<divisions.size(); i++)
    {
        Division div = divisions[i];
        cout << "Here are the quarterly sales for " << div.divName
        << ": ";
        for(int j = 0, quarter = 1; j < 4; ++j, ++quarter)
        {
            cout << "Quarter "<< quarter << " sales: $"<< div.sales[j]
            <<"\n";
        }
    }
}
于 2012-12-17T10:44:14.180 回答
0

第一个问题是由于您在 main 内部而不是在其之前在全局范围内声明要使用的函数引起的: void Intro(); 部门 CreateCorporateFile(); Division DisplayCorporateSales();

第二个问题是由于您i为每个循环使用了两次变量而引起的。您需要使用不同的变量名称(或仅用quarter作循环变量)。

于 2012-12-17T10:45:42.013 回答