0
float deposit (float balance)
{
    float amount[3]; 
    system("cls");
    cout<<"Enter the amount you wish to deposit"<<endl; 
    cin>>amount[3]; 
        balance = balance + amount[3]; 
    writeBalance(balance); 
    return balance;  
}
//This is a function to allow the user to increase their balance 

但是当我在程序的存款部分输入金额时,会出现一个弹出框并显示:

Run-Time Check Failure #2 - Stack around the variable 'amount' was corrupted.

任何帮助都会非常感谢

4

2 回答 2

2

由于您拥有float amount[3];,因此您只能访问amount[0]amount[1]amount[2]。任何其他索引都会为您提供未定义的行为,这是导致程序崩溃的原因。

此外,切勿使用 afloat来表示实际货币。您只能精确到大约 7 个有效数字。double即使准确度(大约 15 位有效数字)会更好,使用 a也是不安全的。您最好的选择是使用货币类型。看看这个问题:Best way to store currency values in C++

于 2014-01-31T11:11:04.343 回答
1

您必须在循环中输入数组的每个元素。按以下方式更改代码

float deposit (float balance)
{
    const size_t N = 3; 
    float amount[N]; 
    system("cls");
    cout<<"Enter the amount you wish to deposit"<<endl;

    for ( size_t i = 0; i < N; i++ )
    { 
        cin>>amount[i]; 
        balance = balance + amount[i];
    }

    writeBalance(balance); 
    return balance;  
}

虽然实际上没有必要使用数组。您可以在一个常规变量中输入数据。

于 2014-01-31T11:15:42.083 回答