[英]How to take a returned value and set it to “x”?
我正在為學校工作,但遇到了問題。 請理解,我對c ++和程序設計總體而言還是一個新手(過去的經驗只是一點點HTML)。 無論如何,這是我的問題。
例如,我是一名在校學生,我想去吃午餐。 我去吃午飯,然后花掉大約x錢,然后將那筆錢帶回主要功能。
int lunch(int moneyL)
{
std::cout << Here is lunch! 4 bucks please";
moneyL - 4
return moneyL;
}
int main()
{
std::cout << "You are given 5 dollars to eat lunch" << std::endl;
int money = 5;
std::cout << "Lets go to lunch";
Lunch(money)
}
同樣,我的問題是(如果我感到困惑)如何將int main中的錢設置為午餐中帶走的錢?
謝謝
有多種解決方法:
解決方案1(按返回值):
int lunch(int moneyL)
{
std::cout << "Here is lunch! 4 bucks please\n";
moneyL = moneyL - 4;
return moneyL;
}
int main()
{
std::cout << "You are given 5 dollars to eat lunch" << std::endl;
int money = 5;
std::cout << "Lets go to lunch\n";
money = lunch(money)
}
解決方案2(參考):
void lunch(int& moneyL)
{
std::cout << "Here is lunch! 4 bucks please\n";
moneyL = moneyL - 4;
}
int main()
{
std::cout << "You are given 5 dollars to eat lunch" << std::endl;
int money = 5;
std::cout << "Lets go to lunch\n";
lunch(money);
}
您需要進行兩項更改:
1) return moneyL - 4;
在功能lunch
而不是該功能的最后兩行中(這也修復了由於缺少而導致倒數第二行的語法錯誤;
)
2) money = Lunch(money)
main
money = Lunch(money)
,因此money
變量將更新。 (目前不需要,但將來會驗證您的代碼)。
C ++中的函數參數按值傳遞。 Google表示更多信息。 繼續前進,看看引用和指針:有一些適合您的替代方法,但是我認為我給您的方法最適合初學者。
您需要通過引用傳遞值,方法是:
#include <iostream>
void Lunch(int& moneyL)
{
std::cout << "Here is lunch! 4 bucks please" << std::endl;
moneyL -= 4; // another thing, this doesnt change anything unless it
// is coded as an assignation
// you dont need to return the value
}
int main()
{
std::cout << "You are given 5 dollars to eat lunch" << std::endl;
int money = 5;
std::cout << "Lets go to lunch" << std::endl;
Lunch(money);
std::cout << "Money now: " << money << std::endl;
}
我尚未閱讀您提出的完整問題。 我的建議是,您應該聲明金錢和午餐是學生班的數據成員。 這樣的事情。
class Student{
public:
int money;
void lunch(){
//implementation of lunch goes here...
// subtract money here
}
};
int main(){
Student s;
s.money = 10;
s.lunch();
return 0;
}
正如πάνταῥεῖ所指出的,最簡單的解決方案是調用
money = Lunch(money);
代替
Lunch(money);
另一個解決方案是,使函數采用“引用”而不是“值”作為參數:
void lunch(int& moneyL)
{
std::cout << Here is lunch! 4 bucks please";
moneyL -= 4;
}
在您的情況下,moneyL變量是main()函數中moneyL的副本。 在我的情況下,通過傳遞int&,Lunch()中的moneyL與main()中的變量相同。 因此,無需返回值。
提示:閱讀“按值和按引用傳遞的參數”一章: http : //www.cplusplus.com/doc/tutorial/functions/
編輯:更正“ moneyL-= 4;” 正如πάνταῥεῖ在評論中寫道。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.