在main中使用函数的局部变量

时间:2013-10-08 11:02:42

标签: c++ function

我试着寻找芒果,但所有的线程都是不同的。

#include <cstdlib>
#include <iostream>
#include <math.h>
using namespace std;

void calcDistance (int x1, int y1, int x2, int y2);

int main()
{
    int x1, y1, x2, y2;
    cout << "Enter the points in coordinate pair form, ommiting parantheses" << endl;
    cin >> x1 >> y1 >> x2 >> y2;

    calcDistance (x1,  y1,  x2,  y2);

    system("pause");
    // how do I cout the dist in main-- says dist isn't declared

}


void calcDistance (int x1, int y1, int x2, int y2)
{
    int sideA;
    sideA = x2 - x1;

    int sideB;
    sideB = y2 -y1;

    int sideAsqd;
    sideAsqd = sideA * sideA;

    int sideBsqd;
    sideBsqd = sideB * sideB;

    int sideCsqd;
    sideCsqd = sideAsqd + sideBsqd;

    double dist;
    dist = sqrt(sideCsqd);

    cout << "The calculated distance is "<< dist << endl;

}

如何让第二个cout出现在main中。我尝试将它放在main中,但后来我得到一个错误,表示dist未在范围中声明。

我希望能够在main中使用dist值,而在函数中计算它。

2 个答案:

答案 0 :(得分:5)

更改您的功能:

double calcDistance (int x1, int y1, int x2, int y2)
{
    int sideA = x2 - x1;

    int sideB = y2 -y1;

    int sideAsqd = sideA * sideA;

    int sideBsqd = sideB * sideB;

    int sideCsqd = sideAsqd + sideBsqd;

    double dist = sqrt(sideCsqd);

    return dist;    
}

主要做这件事:

double res =  calcDistance (x1,  y1,  x2,  y2);
cout << "The calculated distance is "<< res << endl;

答案 1 :(得分:1)

给定一个函数,比如说

void calcDistance (int x1, int y1, int x2, int y2)
{
  //...
  double dist;
  //...
}

变量dist超出了右大括号的范围,因此你不仅可以从其他地方引用它,它在函数外部时也不会存在。
如果您想在其他地方使用该值,请将其返回:

double calcDistance (int x1, int y1, int x2, int y2)
{
  //...
  double dist;
  //...
  return dist;
}

要在别处使用它,只需捕获回报:

double distance = calcDistance(1,2,3,4);

现在您可以使用另一个名为distance的局部变量。