我似乎无法弄清楚这一点。我想做的是宣布三个功能。用户输入值“余额”的一个。另一个显示菜单。我想在“main”函数中调用这些函数,并希望将“balanceAcquired”函数输入的“balance”与它一起使用。
我是c ++的新手,所以我的代码可能很草率,但我得到的错误是
错误C4716:'balanceAcquire':必须返回值
错误C4716:'menu':必须返回值
错误c4700:使用未初始化的本地变量'balance'
// check book balancing program
//header files
#include <iostream>
#include <iomanip>
#include <cmath>
#include <cstdio>
using namespace std;
int balanceAcquire(){
float balance; // balance entered by user
// acquire balance
cout << "check book balancing program \n\n";
cout << "Enter the beginning balance: ";
cin >> balance;
}
int menu(){
//menu
cout << "Commands: \n"; // commands
cout << "C - process a check\n"; // process a check
cout << "D - process a deposit\n"; // process a deposit
cout << "E - End the program\n"; // end the program
}
int main(){
// define variables
const float fee = .25; // fee for transaction
float check, // check amount
deposit, // deposit amount
balance; // balance amount
char choice; // user entered choice
float serviceCharges = 0; // service charges amount tally
// initiate program
balanceAcquire();
menu();
cout << "Enter transaction type: " << endl; // ask for a choice
cin >> choice; // choice type
switch (choice) {
case 'c':
cout << "Enter transaction amount: " << endl;
cin >> check;
cout << "Processing check for" << check << endl;
balance -= check;
cout << "Balance: " << setprecision(2) << balance << endl;
cout << "Service charge: $.25 for a check" << endl;
serviceCharges += fee;
cout << "Total service charges: " << serviceCharges << "\n\n";
break;
case 'd':
cout << "Enter transaction amount: " << endl;
cin >> deposit;
cout << "Processing deposit for" << deposit << endl;
balance += deposit;
cout << "Balance: " << setprecision(2) << balance << endl;
cout << "Total service charges: " << serviceCharges << "\n\n";
break;
case 'e':
cout << "Processing end of month" << endl;
balance -= serviceCharges;
cout << "Final Balance: $" << balance << endl;
break;
}
}
除此之外我试图用这种方式写出来的全部内容是我可以返回“菜单”以允许用户选择更多存款或支票输入,最后收到最终余额减去交易费用。
编辑1:格式化
答案 0 :(得分:2)
通过阅读您的代码,我得出结论,您没有掌握函数调用的工作原理。用一句话来说:
函数体只能与其签名中的内容以及全局状态进行交互。他们不会从他们的来电者那里隐含地继承任何东西。
例如,如果您希望balanceAcquire()
对&#34;外部&#34;即main()
产生影响,则需要自行连接管道。
第一种方式:
int balanceAcquire() {
float b;
//...
cin >> b;
return b;
}
该函数返回值。在外部,您可以使用函数调用表达式作为值来获取它:
int main() {
float balance;
//...
balance = balanceAcquire();
// balance is set.
}
第二种方式:
void balanceAcquire(float &b) {
//...
cin >> b;
}
该函数不返回任何内容(因此void
),但通过引用(b
)传入&
,这意味着它可以从外部直接访问变量。
int main() {
float balance;
//...
balanceAcquire(balance);
// balance is set.
}
答案 1 :(得分:0)
只需按照错误进行操作。
错误C4716:'balanceAcquire':必须返回值
int balanceAcquire() {
*** <== declared to return int, no return in body
错误C4716:'menu':必须返回值
int menu() {
*** <== declared to return int, no return in body
错误c4700:使用未初始化的本地变量'balance'
在您的main函数中,您的代码如下所示:
float balance;
// [ snip ]
balance -= check;
balance += deposit;
balance -= serviceCharges;
这是未定义的行为,您必须在读取之前将balance
初始化为某个值。您可能希望将其分配给balanceAcquire()
的返回值,这应该返回float
:
balance = balanceAcquire();