[英]Question on how I can use and obtain just the value of return after function is executed
我正在為編碼類制作一個有限狀態機。 我如何使用返回值來更改 main 中 int HP 的值,這樣我的代碼就不會有任何其他問題。 我只是想讓它能夠操縱HP的值,並使用HP的新值來實現更多功能。
對不起,如果解決這個問題真的很簡單。 我正在努力理解函數在 C++ 中的工作原理,並且似乎無法在網上或閱讀教程的任何其他地方找到解決方案。
#include <iostream>
#include <time.h>
using namespace std;
int forage(int HP) {
cout << "The ant is in foraging state."<<endl;
if (rand() % 100 < 60) {
cout << "The ant found something!"<<endl;
if (rand() % 100 < 10) {
cout << "The ant found poison!" << endl;
HP -= 1;
}
else {
cout << "The ant found food!" << endl;
HP += 1;
}
}
int mHP = HP;
return mHP;
}
int main() {
srand(time(NULL));
int mHP = 0;
cout << "Welcome to Ant Simulator"<<endl;
forage(10);
cout << mHP;
system("pause");
return 0;
}
你有幾個選擇。 一種可能性是通過引用傳遞HP
,並讓forage
修改傳入的內容:
void forage(int &HP) {
cout << "The ant is in foraging state."<<endl;
if (rand() % 100 < 60) {
cout << "The ant found something!"<<endl;
if (rand() % 100 < 10) {
cout << "The ant found poison!" << endl;
HP -= 1;
}
else {
cout << "The ant found food!" << endl;
HP += 1;
}
}
}
另一種可能性是只使用從forage
返回的結果:
mHP = forage(10);
如果你打算這樣做,你可以添加一個注解,這樣如果你不小心忽略了它返回的值,最近的編譯器會告訴你這個問題:
[[nodiscard]] int forage(int HP) {
// ...
[[nodiscard]]
告訴編譯器你想確保從這個函數返回的值不會像你在問題中的代碼那樣被丟棄。
順便說一句,我也更喜歡將forage
分成幾個單獨的部分。 我更喜歡有一個嚴格處理 UI(顯示關於發生的事情的字符串)和另一個嚴格處理游戲本身邏輯的部分。 作為起點,您可以考慮將流作為參數傳遞,並將forage
顯示到該流:
void forage(int &HP, std::ostream &s) {
s << "The ant is in foraging state.";
if (rand() % 100 < 60) {
s << "The ant found something!\n";
if (rand() % 100 < 10) {
s << "The ant found poison!\n";
HP -= 1;
}
else {
s << "The ant found food!\n";
HP += 1;
}
}
}
如果您決定做類似的事情,這可以幫助將游戲移植到窗口系統下。
換forage(10);
到mHP = forage(10);
您的函數forage
的返回類型為int
。 如果要將此返回值放入變量mHP
,則需要將函數的返回值分配給變量,如上所述。
只是為了添加到以前的答案......以基本了解函數如何與您定義的函數一起工作為例:
int forage(int HP){...}
函數名之前的int
定義了返回類型,所以基本上你的函數在執行結束時返回什么。 然后是您的函數名稱,在本例中為forage
,然后是輸入參數。 在您的情況下,只有一個輸入參數是整數值int HP
。 大括號內的所有代碼都在函數調用時執行。
現在,所有沒有返回類型void
函數在其代碼中的某處(大部分時間在最后)都有一個 return 語句。 實際的返回值被分配給一個變量,如下所示:
int returnedValue;
receivedValue = forage(10);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.