![](/img/trans.png)
[英]Why the main function output 73.4 even if it's return type is int?
[英]Returning the output of a function as the return code of main()
我在這里自學,所以我沒有可用的 model 答案。
處理程序流示例並嘗試基於二進制搜索獲得數字猜測器。 我已經讓它成功運行並捕獲邊緣情況,但一個目標是讓main()
返回所做的猜測次數。 我將主代碼重構為單獨的 function 以使其更清晰,但我無法正確獲取返回代碼,我懷疑它與變量 scope 有關,但無法弄清楚。
#include <iostream>
using namespace std;
int guessNumber(int highest, int lowest, int lAttempts)
{
int guess = lowest + ((highest - lowest) * 0.5);
char response = 'a';
lAttempts++;
cout << "My guess is " << guess << ", am I correct?" << endl;
cout << "(y)es/too (h)igh/too (l)ow/(q)uit" << endl;
cin >> response;
while (response != 'y' && response != 'h' && response != 'l' && response != 'q')
{
cout << "I'm sorry, I didn't understand that" << endl;
cout << "(y)es/too (h)igh/too (l)ow/(q)uit" << endl;
cin >> response;
}
switch (response)
{
case 'y':
cout << "I guessed correctly after " << lAttempts << " attempts";
break;
case 'h':
highest = guess;
guessNumber(highest, lowest, lAttempts);
break;
case 'l':
lowest = guess;
guessNumber(highest, lowest, lAttempts);
break;
case 'q':
cout << "Exiting program";
break;
}
return lAttempts;
}
int main()
{
cout << "Think of a number between 1-100" << endl;
int highest = 100;
int lowest = 0;
int attempts = 0;
attempts = attempts + guessNumber(highest, lowest, attempts);
return attempts;
}
cout
返回正確的嘗試次數,但程序(因此main()
)始終以 1 退出。
我在這里想念什么?
謝謝。
您缺少在 switch 語句中更新您的嘗試變量。
應該是這樣的。
lAttempts = guessNumber(highest, lowest, lAttempts);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.