C ++:每当我尝试查看我的数组时,前两个输入都不会出现

时间:2015-10-14 03:45:02

标签: c++ arrays

而不是前两个输入,它从第三个开始。这导致我的整个阵列移动两个位置,在最后两个位置显示非常小的数字,如1.54831e-315。这是我的第一次提交,所以我道歉,如果我搞砸了某个地方。这是我写的一切

const int ROWS = 3;  
const int COLS = 7;

double inputFood();  
void printFood();  
void avgFood();  
void leastFood();  
void largestFood();

int main()
{

    string day;
    double monkeys[ROWS][COLS];
    double avg, sum = 0, largest = monkeys[0][0], least = monkeys[0][0];

    inputFood();
    printFood();
    avgFood();
    leastFood();
    largestFood();



    return 0;
}

double inputFood()  
{
    string day;
    double monkeys[ROWS][COLS];

    for (int r = 0; r < ROWS; r++)
    {
        for (int c = 0; c < COLS; c++)
        {
            switch(c)
            {
                case 0: day = "Sun";
                    break;
                case 1: day = "Mon";
                    break;
                case 2: day = "Tue";
                    break;
                case 3: day = "Wed";
                    break;
                case 4: day = "Thu";
                    break;
                case 5: day = "Fri";
                    break;
                case 6: day = "Sat";
                    break;
                default: cout << "No corresponding day. " << endl;
            }

            cout << "Enter pounds of food eaten by monkey " << r + 1 << " on " 
                 << day << ": " << endl;
            cin >> monkeys[r][c];   

            if (monkeys[r][c] < 0)
            {
                cout << "A monkey cannot eat a negative amount of food. " << endl;
                cout << "Enter the correct pounds of food eaten by monkey " << r + 1
                     << " on " << day << ": " << endl;
                cin >> monkeys[r][c];
            }

        }
    }
}

void printFood()  
{
    double monkeys[ROWS][COLS];

    cout << "Monkey\tSun\tMon\tTue\tWed\tThu\tFri\tSat" << endl;
    cout << "-----------------------------------------------------------" << endl;
    for (int r = 0; r < 3; r++)
    {
        cout << "     " << r + 1;
        for (int c = 0; c < 7; c++)
        {
            cout <<"\t" << monkeys[r][c];
        }
        cout << endl;
    }
}

1 个答案:

答案 0 :(得分:0)

这是你的问题:

double inputFood()  
{
    string day;
    double monkeys[ROWS][COLS];

您已在函数内部重新定义了一个数组,并且该函数在函数终止后消失。主函数中的数组保持不变。

函数inputFood应该以{{1​​}}为参数。

在C或C ++中,变量不会被零初始化,它们会将其先前的值保留在内存中。如果您遇到像monkey这样的疯狂数字,请考虑该变量尚未由您初始化。

<强>更新

在主要功能中将x10^-315传递给monkeys

inputFood

并改变:

inputFood(monkeys);

成:

double inputFood()  
{
    string day;
    double monkeys[ROWS][COLS];
    for (int r = 0; r < ROWS; r++)
    ....