我正在无限期地在一个函数(double)上用C ++循环创建一个软件。在第一次循环之后,第二次运行循环,它返回'nan'。我哪里出错了。
int main()
{
double Balance = 100;
for (int i = 0; i < 5; i++) {
nyaradzo(Balance, i);
}
}
double nyaradzo(double bal, int pass)
{
int x = bal;
double Amount;
string policy_number;
double confirmation;
cout<<"WELCOME TO NYARADZO ONLINE POLICY PAYMENT"<<endl;
cout<<"ENTER YOUR POLICY NUMBER"<<endl;
cin>>policy_number;
cout<<"ENTER AMOUNT YOU WISH TO PAY FOR YOU POLICY"<<endl;
cin>>Amount;
cout<<"YOUR POLICY NUMBER IS: "<<policy_number<<endl;
cout<<"YOU HAVE CHOSEN TO PAY $"<<Amount<<" FOR YOUR FUNERAL POLICY. \n Is this information correct?"<<endl;
cout<<"1 TO CONFIRM"<<endl;
cout<<"2 TO CANCEL"<<endl;
cin>>confirmation;
if (confirmation==1) {
if (Amount <= x) {
x -= Amount;
cout<<"Transaction Complete"<<endl;
cout<<"YOUR BALANCE IS $"<<x<<endl;
return x;
}
else if (Amount > x) {
cout<<"TRANSACTION DENIED \a"<<endl;
cout<<"You cannot withdraw more than your actual balance..."<<endl;
return 0;
}
else {
cout <<x << endl;
cout<<"TRANSACTION DENIED \a"<<endl;
cout<<"Your purchase must be greater than or at least equal to $1"<<endl;
return 0;
}
}
else if (confirmation==2) {
cout<<"YOU HAVE CHOSEN TO CANCEL YOUR ZESA TRANSACTION"<<endl;
// transaction(bal, pass);
}
else
{
cout << "Invalid selection" << endl;
return 0;
}
}
当它第二次进入循环时,它会失败。
答案 0 :(得分:0)
并非nyaradzo
中的所有路径都返回值。您应该启用所有编译器警告。它应该提醒你这一点。由于x = bal
并且您只在amout确定时修改x,因此将其添加为func的最后一行:
return x;
将x
的类型更改为double
。或者摆脱x
并始终使用bal
。
另外,我假设您想保持运行平衡。然后你应该将for循环更改为:
for (int i = 0; i < 5; i++) {
Balance = nyaradzo(Balance, i);
}