繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM