首页 > 解决方案 > 在函数中传递多个变量?

问题描述

我是一名 CS 一年级学生,试图更好地理解 C++ 中的函数,因为我现在在这方面很薄弱。我正在尝试创建一个程序,该程序将向用户询问两个整数,然后将其传递给计算函数,该函数最终将传递给显示函数以显示计算结果。截至目前,这是我的代码,底部有输出。我不太确定为什么 num1 和 num2 没有正确传递给计算函数?任何帮助表示赞赏,请忽略风格,我通常会在我开始工作后尝试清理它。

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

void getData();
void doTheMath(int num1, int num2);
void displayResults(int num1, int num2, int& sum, int& diff, int& prod, int& quot, int& rem);

int main()
{
    int num1;
    int num2;
    int sum;
    int diff;
    int prod;
    int quot;
    int rem;
    getData();
    doTheMath(num1, num2);
    displayResults(num1, num2, sum, diff, prod, quot, rem);

    system("pause");
    return 0;
}



void getData()
    {
    int num1;
    int num2;
    cout << "Please enter two integer values:\n";
    cin >> num1;
    cin >> num2;

    cout << "The first number is " << num1 
        << " and the second is "<< num2 << "\n\n";
}



void doTheMath(int num1, int num2)
{
        int sum = num1 + num2;
        int diff = num1 - num2;
        int prod = num1 * num2;
        int quot = num1 / num2;
        int rem = num1 % num2;
}



void displayResults(int num1, int num2, int& sum, int& diff, int& prod, int& quot, int& rem)
{
    if (num2 == 0)
    {
        cout << "Here are the results:\n\n";
        cout << "The sum of " << num1 << " and " << num2
            << " is " << sum << ".\n";
        cout << "The difference, (" << num1 << " minus "
            << num2 << ") is " << diff << ".\n";
        cout << "The product of " << num1 << " and "
            << num2 << " is " << prod << ".\n";
        cout << "Cannot divide by zero.\n\n";
    }
    else
    {
        cout << "Here are the results:\n\n";
        cout << "The sum of " << num1 << " and " << num2
            << " is " << sum << ".\n";
        cout << "The difference, (" << num1 << " minus "
            << num2 << ") is " << diff << ".\n";
        cout << "The product of " << num1 << " and "
            << num2 << " is " << prod << ".\n";
        cout << num1 << " divided by " << num2 << " is "
            << quot << " with a remainder of " << rem
            << ".\n\n";
    }

}

//Output
/*Please enter two integer values:
12
0
The first number is 12 and the second is 0

Here are the results:

The sum of -858993460 and -858993460 is -858993460.
The difference, (-858993460 minus -858993460) is -858993460.
The product of -858993460 and -858993460 is -858993460.
-858993460 divided by -858993460 is -858993460 with a remainder of     -858993460.

Press any key to continue . . .*/

标签: functionvisual-c++

解决方案


main() 中的 num1 和 num2 变量与 getData() 中的 num1 和 num2 是不同的变量。所以你在 getData() 中设置了这些,但除了显示之外什么都不做。main() 中的 num1 和 num2 不受影响。将这些(作为参考)传递给 getData(int &num1, int &num2) 并且不要在 getData() 本身中声明它们。阅读“自动”变量声明(在堆栈上声明)。


推荐阅读