2016-10-20 117 views
-4

我的函數包含字符串和整數,但在運行它時,我得到錯誤:函數返回銀行賬戶餘額

error: could not convert 'balance' from 'int' to 'std::string {aka std::basic_string<char>}'

我試圖做到的是寫一個程序,如果你想將問到'存款'或'取款'。 然後,程序會提示一美元(整數值)。編寫'update_balance'函數以適當修改您的餘額。如果命令是「存款」,您的功能應該將美元金額添加到當前餘額;如果命令是'撤回',你的函數應該從當前餘額中減去美元金額。

命令執行完成後返回新餘額。

我當前的代碼是:

#include <iostream> 
#include <string> 
using namespace std; 
//************************FUNCTION TO BE FIXED************************ 
void update_balance(string command, int dollars, int balance) 
{ 
    if (command == "withdraw") 
    { 
     balance = balance - dollars; 
    } 
    else 
    { 
     balance = balance + dollars; 
    } 
} 
//************************FUNCTION TO BE FIXED************************ 

int main() 
{ 
    //the amount of money in your account 
    int balance = 0; 

    // Command that will tell your function what to do 
    string command; 
    cin >> command; 

    // number of dollars you would like to deposit or withdraw 
    int dollars = 0; 
    cin >> dollars; 

    balance = update_balance(balance, dollars, command); 

    // Prints out the balance 
    cout << balance << endl; 

    return 0; 
} 
+0

你混了順序的參數和預期回報與/無效。我的意思是'balance = update_balance(balance,dollars,command);'不匹配'void update_balance(string command,int dollars,int balance)'。 – drescherjm

+0

您仍然沒有注意到返回值。從你的使用update_balance應該返回一個int。所以,而不是'無效update_balance(字符串命令,int美元,int餘額)'你需要'int update_balance(字符串命令,美元,int餘額)'不要忘記'返回餘額;' – drescherjm

+0

我做了你的更改指導我和它的工作。我只需要弄清楚如何標記你的幫助作爲回答 – 4rb3l

回答

0

我發現了一些錯誤。這是我的建議。 設置餘額= 500,而不是0 變化

void update_balance(string command, int dollars, int balance) 

int update_balance(int balance, int dollars, string command) 

中的if-else循環後添加一條線。

return balance; 

添加int balancen。

變化

balance = update_balance(balance, dollars, command); 

balancen = update_balance(balance, dollars, command); 
+0

最後一部分是不需要的。您可以將其保留爲「平衡」。 – drescherjm

0

我建議你通過引用或指針,像這樣傳遞參數:

#include <iostream> 
#include <string> 
using namespace std; 

void update_balance(string command, int& balance, int dollars) 
{ 
    if (command == "withdraw") 
     balance -= dollars; 
    else 
     balance += dollars; 
} 

int main() 
{ 
    //the amount of money in your account 
    int balance = 0; 

    // Command that will tell your function what to do 
    string command; 
    cin >> command; 

    // number of dollars you would like to deposit or withdraw 
    int dollars = 0; 
    cin >> dollars; 

    update_balance(command, balance, dollars); 

    // Prints out the balance 
    cout << balance << endl; 

    return 0; 
}