这是我的第一篇文章;抱歉,出现任何格式错误。为什么第二个get_wager_amount()不被使用(程序终止),我该如何解决呢?或者任何使代码更好的东西将不胜感激。代码如下:
int get_bank_balance(){
cout << "Enter an initial bank balance (dollars): " << endl;
cin >> balance;
return balance;
}
int get_wager_amount(){
cout << "\nEnter a wager (dollars)" << endl;
cin >> wager;
}
bool is_valid_wager_amount(){
if(wager <= balance){
return true;
}
if(wager > balance){
cout << "Error: wager > balance. Try again" << endl;
return false;
}
}
int main()
{
get_bank_balance();
get_wager_amount();
is_valid_wager_amount();
if (is_valid_wager_amount == false){
get_wager_amount();
is_valid_wager_amount();
}
答案 0 :(得分:2)
is_valid_wager_amount();
if (is_valid_wager_amount == false)
正在调用is_valid_wager_amount
,丢弃结果,然后测试is_valid_wager_amount
函数的地址以查看其是否为假。这不是特别有用。最新的编译器应拒绝此代码。
相反,给予
if (is_valid_wager_amount() == false){
尝试。这将调用is_valid_wager_amount
函数,并检查结果是否为假。
不相关:请考虑将if
替换为while
,以反复询问直到用户提供有效答复为止。
答案 1 :(得分:0)
int函数返回int值,因此,如果以后需要使用它们,请将其保存为变量。
#include <iostream> //1
using namespace std;
int get_bank_balance()
{
int balance; //2
cout << "Enter an initial bank balance (dollars): " << endl;
cin >> balance;
return balance;
}
int get_wager_amount()
{
int wager; //2
cout << "\nEnter a wager (dollars)" << endl;
cin >> wager;
return wager;
}
bool is_valid_wager_amount(int balance,int wager)//3
{
if(wager <= balance)
{return true;}
else
{
cout << "Error: wager > balance. Try again" << endl;
return false;
}
}
int main()
{
int balance = get_bank_balance(); //4
int wager = get_wager_amount(); //4
if (is_valid_wager_amount(balance, wager)){
//another function here, for example:
cout<<"Your balance: "<<balance-wager<<endl;
}
}