C:警告:’withdraw_amt’可以在此function中未初始化使用
我正在为C类的介绍编写一个程序,并在尝试使用gcc编译时不断收到警告。
这是我的代码:
int main () { float balance; float beg_balance; float withdrawal_amt; float deposit_amt; float amount; int total_withdrawals; int total_deposits; int selection; print_greeting (); printf("Let's begin with your beginning balance"); beg_balance = get_positive_value(); do { print_menu (); scanf("%d", &selection); switch (selection) { case WITHDRAWAL: get_positive_value(); balance = withdrawal(balance, withdrawal_amt, amount); break; case DEPOSIT: get_positive_value(); balance = deposit(balance, deposit_amt, amount); break; case SUMMARY: print_receipt(total_withdrawals, total_deposits, beg_balance, balance, \ withdrawal_amt, deposit_amt); break; case QUIT: break; default: printf("Invalid selection"); break; } } while(selection != 4); return 0;
我在编译时遇到的错误是这样的:
project.c: In function 'main': project.c:46: warning: 'withdrawal_amt' may be used uninitialized in this function project.c:46: warning: 'amount' may be used uninitialized in this function project.c:50: warning: 'deposit_amt' may be used uninitialized in this function project.c:53: warning: 'total_withdrawals' may be used uninitialized in this function project.c:53: warning: 'total_deposits' may be used uninitialized in this function
有什么想法吗? 谢谢
编辑:
现在我无法创建用于打印帐户交易历史记录的寄存器function。 它应打印出期初和期末余额,以及显示已发生的所有交易(存款和取款)的表格。 任何帮助将不胜感激
float balance; float beg_balance; float withdrawal_amt; float deposit_amt;
你永远不会赋予它们任何价值。 就像你写的那样:
case DEPOSIT: get_positive_value(); balance = deposit(balance, (float), amount); break;
你需要初始化它们:
float withdrawal_amt = 0.0;
您获得的错误不是错误,而是警告。 他们指出您没有初始化任何自动存储变量,因此它们将以未指定的值启动。
您可以初始化变量,比如说0
,警告就会消失。
我想你想要使用你的函数get_positive_value()
如下所示:
withdrawal_amt = get_positive_value();
和其他人一样。
您正在传递withdrawal_amt
, amount
和警告中未提及的其他变量。
请注意,在某个函数内声明的所有变量都存储在编译器选择的某个随机内存(堆栈内存)位置,并且该位置可能包含一些垃圾值,这些值将作为变量的初始值。
因此编译器会事先指示您将它们初始化为某个已知值,这样当您“存入” 1000.00 USD
时,您就不会获得银行余额-1000.00 USD
1000.00 USD
😉