我尝试搜索遮阳篷,但是所有线程都是不同的lang。
#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;
}
我如何使第二次发生在main中。我尝试仅将其放在main中,但是随后出现一个错误,提示dist未在范围中声明。
我希望能够在main中使用dist值,而该值已在函数中计算出来。
最佳答案
更改您的功能:
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;
关于c++ - 在main中使用函数的局部变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19245995/