如何获取返回值并将其设置为 "x" ?

How to take a returned value and set it to "x"?

本文关键字:设置 何获取 获取 返回值      更新时间:2023-10-16

我正在为学校做一些事情,但我遇到了一个问题。请理解我对 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 pleasen";
    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 lunchn";
    money = lunch(money)
}

解决方案2(通过引用(:

void lunch(int& moneyL)
{
    std::cout << "Here is lunch! 4 bucks pleasen";
    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 lunchn";
    lunch(money);
}

您需要进行两项更改:

1(return moneyL - 4;函数lunch而不是该函数中的最后两行(这也修复了由于缺少;而倒数第二行的语法错误(

2( money = Lunch(money) main,以便更新money变量。(目前不是必需的,但将来会证明您的代码(。

C++中的函数参数按传递。谷歌一下了解更多细节。展望未来,看看参考资料和指针:有适合你的替代公式,但我认为我给你的公式对初学者来说是最好的。

您需要通过引用传递值,这样:

#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;",因为πάντα ῥεῖ在评论中写道。