我的功能不会互动。那或它不会返回值

时间:2014-04-07 07:17:01

标签: c++

所以我一直在这方面工作,没有运气。第一个函数正在工作,因为我通过对每个变量使用cout来确认它,并且方程是正确的,因为我在没有函数的情况下尝试了它。问题是function1engineer没有为一个值赋值,所以它变为默认的double值。如何让function1engineer接受第一个函数的输入?

这是我的代码。

#include <iostream>
#include <cmath>
#include <math.h>
#include <iomanip>
#define PI 3.14159265
using namespace std;
//angle*PI/180 to work in c++ for angles.
void function1customer(double& x1, double& x2, double& y1, double& y2);
double function1engineer(double distance, double x1, double x2, double y1, double y2);

int main()
{
    int exitLoop;
    do
    {


        cout << "Choose an option.\n1: Given two points, compute the distance between them."
            << "\n2: Given two points, compute the horizontal angle from \nthe first point to the second."
            << "\n3: Given the elevation angle and velocity, compute the \n(horizontal) distance an object travels."
            << "\n4: Given a starting point, a distance, and a horizontal angle, \ncompute the destination point."
            <<endl;
        int opselect;
        cin >> opselect;
        switch(opselect)
            {
                //compute distance between 2 points
        case 1:
        double distance;
        double x1, x2, y1,y2;
        function1customer(x1,x2,y1,y2);
        cout << x1 << endl << x2 << endl << y1<< endl << y2 << endl;
        function1engineer;
        cout << setprecision(2)<< distance << endl;
        break;
            }
    cout << "Would you like to perform another calculation?\n0=No\n1=Yes" <<endl;
    cin >> exitLoop;
    }   
    while(exitLoop != 0);
}

void function1customer(double& x1, double& x2, double& y1, double& y2)
{
    cout << "Enter X1 cordinate in feet" <<endl;
    cin >> x1;

    cout << "Enter X2 cordinate in feet" <<endl;
    cin >> x2;

    cout << "Enter Y1 cordinate in feet" <<endl;
    cin >> y1;

    cout << "Enter Y2 cordinate in feet" <<endl;
    cin >> y2;
}

double function1engineer(double distance, double x1, double x2, double y1, double y2)
{
    distance = 0;
    distance = pow(  ( pow((x2-x1),2.0) + pow((y2-y1),2.0)     ),(1.0/2));
    return distance;
}

2 个答案:

答案 0 :(得分:1)

您需要通过引用传递distance,并且无需显式返回它。 (正如您对function1customer的参数所做的那样。使用此:

void function1engineer(double& distance, double x1, double x2, double y1, double y2)

调用代码为:

function1engineer(distance,x1,x2,y1,y2);

答案 1 :(得分:0)

在使用变量之前,必须始终初始化变量。您还可以向function1engineer添加一个cout语句,以确保它正在计算正确的值。

可以通过将其用作参考或通过在主函数中收集其值来收集距离的修改值。修改后的程序将是。

double function1engineer(double distance, double x1, double x2, double y1, double y2)
{
    distance = 0;
    distance = pow(  ( pow((x2-x1),2.0) + pow((y2-y1),2.0)),(1.0/2));
    cout << "Distance" << distance << endl;
    return distance;
}

将main函数中的调用修改为

distance = function1engineer;