我正在为学校工作,但遇到了问题。请理解,我对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);
}

10-06 07:41