嵌套For循环(C ++)不能正常工作

时间:2013-10-25 15:21:30

标签: c++

我正在编写一些编程作业,我正在尝试使用for-loop来促进编码过程。这是循环:

#ifndef DIVSALES_H
#define DIVSALES_H

class DivSales
{
    public:
        DivSales(){ quarterSales[4] = {0}; };
        double getTotalSales() { return totalSales;}
        static void setTotalSales(double);
        static void addTotalSales(double);
        double getQuarterSales(int numQuarter) {return quarterSales[numQuarter];}
        void setQuarterSales(int numQuarter, double numAmount) { quarterSales[numQuarter] = numAmount;}
    private:
        static double totalSales;
        double quarterSales[];
};

double DivSales::totalSales = 0;
void DivSales::setTotalSales(double totalAmount) {totalSales = totalAmount; }
void DivSales::addTotalSales(double addAmount) {totalSales += addAmount; }
#endif // DIVSALES_H

#include <iostream>
#include "DivSales.h"

using namespace std;

int main()
{
    const int NUMDIVS = 6;
    const int NUMQUARTERS = 4;
    double amount = 0;

    DivSales divs[NUMDIVS];

    for(int division = 0; division < NUMDIVS; division++)
    {
        cout << "Division " << (division + 1) << endl;

        for(int quarter = 0; quarter < NUMQUARTERS; quarter++)
        {
            cout << "Quarter " << (quarter + 1) << ": ";
            cin >> amount;

            divs[division].setQuarterSales(quarter, amount);
            DivSales::addTotalSales(amount);
        }
    }


    return 0;
}

输出示例:

Division 1
Quarter 1: 500
Quarter 2: 500
Quarter 3: 500
Quarter 2: 500
Quarter 3: 500
Quarter 2: 500
Quarter 3: 500
Quarter 2: 500
Quarter 3: 500
Quarter 2: 

我想要做的是,当我输入分区的4个季度的数字时,它将移动到下一个分区。但是,在4个输入后,它不会递增for-loop的除法变量,而是继续要求更多输入。发生了什么事?

2 个答案:

答案 0 :(得分:2)

我找到了导致该问题的原因,它位于文件DivSales.h中:

更改此行:

double quarterSales[];

对于这一行:

double quarterSales[4];

问题是你没有为4个元素的数组分配内存。要初始化它,请将构造函数更改为:

DivSales():quarterSales({0}){ };

您还应将以下行移至DivSales.cpp,否则我收到多个定义错误:

double DivSales::totalSales = 0;

答案 1 :(得分:0)

这里:

divs[division].setTotalSales(amount);
你可能想要:

divs[division].addTotalSales(amount);

但这不是造成问题的原因。哪个我无法重现。