【问题标题】:How to return a variable from one function in C++ to main then use it in another function?如何将变量从 C++ 中的一个函数返回给 main,然后在另一个函数中使用它?
【发布时间】:2016-11-09 05:21:25
【问题描述】:

好的,所以我有一个卡路里计算器,它应该分为五个功能,包括下面的主要功能。我的问题是我得到一个编译器错误,因为 inputNumber 函数和 calculateCalories 函数中的变量一旦获得,就不能被任何其他函数读取。我不允许使用全局变量。我必须缺少一些东西才能读取主函数中的变量,然后将它们输出到其他函数中以获得正确的输出。任何帮助,将不胜感激。 下面是代码:

#include <iostream>
#include <string>
#include <iomanip>

using namespace std;

int main()
{
    int Lbs, hourr, hourW, hourWe, hourb;
    double calBad, calRun, calWal, calWei;
    string name;

    cout << "Welcome to Megan McCracken's Workout Calculator!" << endl;
    cout << endl;

    cout << "Please enter your name: ";
    getline(cin, name);

    inputNumber(Lbs, hourr, hourW, hourWe, hourb);

    calculateCalories(Lbs,hourr,hourb,hourW,hourWe,calBad,calRun,calWal,calWei);

    displayHeadings(name);

    displayLine(hourr,hourb,hourW,hourWe,calBad,calRun,calWal,calWei);

    system("pause");
    return 0;
}

int inputNumber(int Lbs, int hourr, int hourb, int hourW, int hourWe)
{
    cout << "Please enter your weight: ";
    cin >> Lbs;
    return Lbs;
    cout << "Please enter the minutes spent playing badminton: ";
    cin >> hourb;
    return hourb;
    cout << "Please enter the minutes spent running: ";
    cin >> hourr;
    return hourr;
    cout << "Please enter the minutes spent walking: ";
    cin >> hourW;
    return hourW;
    cout << "Please enter the minutes spent lifting weights: ";
    cin >> hourWe;
    return hourWe;
    cout << endl;
}

double calculateCalories(int Lbs, int hourW, int hourb, int hourr, int hourWe, double calBad, double calRun, double calWal, double calWei)
{
    const double Badburn = .044, Runburn = .087, Walkb = .036, Weightb = .042;
    double calBad, calRun, calWal, calWei;
    calBad = (Badburn * Lbs) * hourb;
    calRun = (Runburn * Lbs) * hourr;
    calWal = (Walkb * Lbs) * hourW;
    calWei = (Weightb * Lbs) * hourWe;
    return calBad;
    return calRun;
    return calWal;
    return calWei;
}

void displayHeadings(string name)
{
    cout << "Here are the results for " << name << ": " << endl;
    cout << endl;

    cout << "Activity" << right << setw(18) << "Time" << right << setw(10) << "Calories" << endl;
    cout << "--------------------------------------" << endl;
}

void displayLine(int hourb,int hourr, int hourW, int hourWe, double calBad, double calRun, double calWal, double calWei)
{
    int HB, MB, HR, MR, HW, MW, HWE, MWE, Hour, Min;
    double Calorie;
    HB = (hourb / 60);
    MB = (hourb % 60);
    HR = (hourr / 60);
    MR = (hourr % 60);
    HW = (hourW / 60);
    MW = (hourW % 60);
    HWE = (hourWe / 60);
    MWE = (hourWe % 60);

    Calorie = calBad + calRun + calWal + calWei;
    Hour = (hourb + hourr + hourW + hourWe) / 60;
    Min = (hourb + hourr + hourW + hourWe) % 60;

    cout << "Badminton" << right << setw(14) << HB << ":" << setfill('0') << setw(2) << MB << setfill(' ') << right << setw(10) << setprecision(3) << fixed << showpoint << calBad << endl;

    cout << resetiosflags(ios::fixed | ios::showpoint);

    cout << "Running" << right << setw(16) << HR << ":" << setfill('0') << setw(2) << MR << setfill(' ') << right << setw(10) << setprecision(3) << fixed << showpoint << calRun << endl;

    cout << resetiosflags(ios::fixed | ios::showpoint);

    cout << "Walking" << right << setw(16) << HW << ":" << setfill('0') << setw(2) << MW << setfill(' ') << right << setw(10) << setprecision(3) << fixed << showpoint << calWal << endl;

    cout << resetiosflags(ios::fixed | ios::showpoint);

    cout << "Weights" << right << setw(16) << HWE << ":" << setfill('0') << setw(2) << MWE << setfill(' ') << right << setw(10) << setprecision(3) << fixed << showpoint << calWei << endl;

    cout << "--------------------------------------" << endl;

    cout << resetiosflags(ios::fixed | ios::showpoint);

    cout << "Totals" << right << setw(17) << Hour << ":" << setfill('0') << setw(2) << Min << setfill(' ') << right << setw(10) << setprecision(3) << fixed << showpoint << Calorie << endl;
    cout << endl;
}

【问题讨论】:

  • 您缺少的是通过引用传递参数的概念。你还记得在课堂上讨论过这个话题吗?
  • 不幸的是,通过引用传递参数是该类的下一部分。我们不应该在本节中使用它。无论如何,使用按引用传递仍然会给我一个编译器错误...
  • 然后使用指针。你还记得在课堂上讨论过指针的主题吗?
  • 梅根,也许,只是也许,你的教育工作者正试图让你提前思考 :-) 我们大学有一个人在一年中大部分时间都在隔离,所以花时间学习COBOL 的报告作者,而我们其他人则因大量源代码的报告方式而受苦(在这里显示我的年龄)。不用说,他在这一年取得了优异的成绩,因为他的代码大约是其他人的 10%。当 C++ 语言提供了相当好的功能时(尤其是当关于 SO 的 97.2%* 的 C 问题涉及指针问题时)使用指针来模拟 C++ 中的传递引用是一个坏主意。
  • * 从我的后端提取的统计数据 - 实际值可能大不相同 :-)

标签: c++ function variables return-value main


【解决方案1】:

如果你想在 C++ 的函数中修改传入的变量,你应该通过引用传递它们(默认是通过值,这意味着你得到一个变量的 副本,这实际上是函数退出时丢弃)。

所以,举例来说:

void xyzzy (int plugh) { plugh = 42; }
int main() {
    int twisty = 7;
    xyzzy (twisty);
    cout << twisty << '\n';
    return 0;
}

将输出7,因为twisty 是按值传递的,并且在函数内对其所做的更改不会回显给调用者。

但是,如果您通过 reference 传递:

void xyzzy (int &plugh) { plugh = 42; }
//              ^
//              This does the trick.

然后你会发现它会根据需要输出42

对于您的特定情况,您想查看inputNumber 的参数列表中的变量:

int inputNumber(int Lbs, int hourr, int hourb, int hourW, int hourWe)

您想要回显给调用者的任何这些(粗略一看似乎都是)应该通过引用传递而不是通过值传递。

您还应该查看calculateCalories,因为那是在做同样的事情。请记住,只有您想要更改并回显给调用者的那些需要通过引用传递。所以这只是以cal开头的那些。

而且,由于您使用传递引用来修改变量,因此绝对没有理由从该函数返回任何内容,因此可以将其指定为 void calculateCalories ... 并删除 return 语句(在任何在这种情况下,只有第一个 return 会实际执行任何操作,其他代码将是无法访问的代码)。


如果您还没有达到可以在课堂作业中使用参考的程度(正如您的一位 cmets 所指出的那样),您可以做 C 编码员几十年来一直在做的事情, 使用指针传递引用。就上面的简化示例而言,这意味着修改函数以接收指向您要更改的项目的指针,更改它指向的内容,并使用要更改的变量的地址调用它:

void xyzzy (int *pPlugh) { *pPlugh = 42; }
int main() {
    int twisty = 7;
    xyzzy (&twisty);
    cout << twisty << '\n';
    return 0;
}

但是,它不能很好地替代真实的东西,如果您的教育工作者试图教您,这就像他们让您使用 printf/scanf 而不是 cout/cin 进行用户 I/O :这在 C++ 中当然是可能,因为该语言包含遗留 C 的东西,但它并不是真的教你 C++ 的方式。

声称自己是 C++ 开发人员但实际上使用 C++ 编译器在 C 中编写代码的人是一个相当奇怪的品种,我喜欢称其为 C+ 开发人员——他们从未真正正确地接受该语言。人们越早放下遗留的东西,他们作为 C++ 开发人员就会越好。

【讨论】:

  • 好的,所以我在看下一个赋值,我们应该在那个赋值中使用引用变量,有没有办法使用我的代码将数字返回给主函数,以便它除了指针或引用变量之外的其他函数可以使用吗?
  • @Megan,从函数中获取信息的方法有限:(1) 全局变量,不是一个好主意; (2) 返回值,只有一件事,虽然它可能是一个包含很多东西的struct; (3) 通过引用传递,无论是指针模拟还是真实的。如果您不允许使用全局变量并且您不想使用 pass-by-ref,则选项 2 可能是剩下的最佳选项。
【解决方案2】:

通过引用传递变量。然后函数将能够编辑它们。

您的另一个解决方案(不是一个好主意,但仍然有效)是创建一个结构/类并让函数返回它。


附:如果函数按此顺序排列,您的代码将无法工作,除非您在开头添加它们的签名:

int main();
int inputNumber(int,int,int,int,int);
//and so on

【讨论】:

    【解决方案3】:

    在输入数字中,你不能使用'return'来返回每个值——它会执行第一个return语句。

    在 C++ 中,您可以使用按引用传递,以便将分配给变量的值传回。

    在这种情况下,通过输入变量将是 inputNumber,因此使用 '&' 表示变量是引用:

    void inputNumber(int &Lbs, int &hourr, int &hourb, int &hourW, int &hourWe)
    {
    .
    .
    .
    }
    

    calculateCalories 的类似想法,去掉回报:

    void calculateCalories(int Lbs, int hourW, int hourb, int hourr, int hourWe, double &calBad, double &calRun, double &calWal, double &calWei)
    {
    .
    .
    }
    

    请注意,我们只需要将要传回的变量传递给引用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-03
      相关资源
      最近更新 更多