0

我正在编写一个程序,它将请求用户输入 INT,并将其存储在 [10] 的数组中。我希望能够让用户选择选项 DISPLAY 并查看数组中的所有数据。我只是想不通,这是我到目前为止所拥有的:

case 2 : {
                 int SamtW;
                 cout << " Please enter how much you would like to withdraw "<< endl;
                 cin >> SamtW;
                 sa.doWithdraw(SamtW);
                 break;
             }

这是上面调用的函数:

int saving:: doWithdraw(int amount)
{
    for (int i = 0; i < 10; i++)
{
     last10withdraws[amount];
    }
    if (amount > 1)
    {
    setBalanceW(amount);
    }
    else {
        cout << " ERROR. Number must be greater then zero. " << endl;
    }
    return 0;
}

我相信这会将用户输入放入字符串 last10withdraws 中。然后我希望用户能够调用这个函数:

string saving::display()
{
    last10withdraws[10];
    return 0;
}

这将有望显示数组的内容。关于我做错了什么的任何想法?

4

2 回答 2

1
last10withdraws[10];

这没有任何作用。这将获取数组的第 11 个元素(不存在)的值,然后将其丢弃。

同样是这样:

 last10withdraws[amount];

获取元素的值last10withdraws并将其丢弃。它不会为它分配任何值或将其存储在任何地方。

我想你想要:

int saving:: doWithdraw(int amount)
{
    if (amount > 0)
    {
        for (int i = 9; i != 0; i--)
        { // move the 9 elements we're keeping up one
            last10withdraws[i] = last10withdraws[i-1];
        }
        last10withdraws[0] = amount; // add the latest
        setBalanceW(amount);  // process the withdraw
    }
    else
    {
        cout << " ERROR. Number must be greater then zero. " << endl;
    }
    return 0;
}
于 2013-04-17T18:06:49.557 回答
0

好的 从您的评论中:

首先,您需要一个额外的变量,saving例如nr_of_withdraws. 它将跟踪withdraws已制作的数量。并且在构造类时应该将其分配为零。

然后每次你插入到last10withdraws你增量nr_of_withdraws。如果nr_of_withdraws大于 9,则您的数组已满,您需要对其进行处理。所以...


// Constructor.
saving::saving {
    nr_of_withdraws = 0;
}

// doWithdraw
int saving:: doWithdraw(int amount)
{
    // See if you have space
    if(nr_of_withdraws > 9)
       cout << "last10withdraws are done. Slow down."
       return 0;
    }
    // These lines. oh thy are needed.
    last10withdraws[nr_of_withdraws] = amount;
    nr_of_withdraws++;

    if (amount > 1)
    {
        setBalanceW(amount);
    }
    else {
        cout << " ERROR. Number must be greater then zero. " << endl;
    }
    return 0;
}
于 2013-04-17T18:14:37.183 回答