我的函数包含一个字符串和整数,但在运行时我得到错误:
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 :(得分: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);
答案 1 :(得分: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;
}