Home > Net >  Why q is not equal to 1.0?
Why q is not equal to 1.0?

Time:11-21

I'm a neophyte with c . I wrote this code but the result for q have to be 1.0, but the code give me, changing the variable's order when I recall function "intercetta", for example -34, 0, 9.75. Why?

#include <iostream>
using namespace std;

float coefficienteAngolare(float x1, float x2, float y1, float y2, float m) {
    return m = ((y2 - y1) / (x2 - x1));
}
float intercetta(float m, float x1, float y1, float q) {
    return q = y1 - m * x1;
}
int main() {
    float x1, x2, y1, y2, m=0, q=0;
    x1 = 3.5;
    x2 = 6.5;
    y1 = 9.75;
    y2 = 17.25;
    cout << "m= " << coefficienteAngolare(x1, x2, y1, y2, m) << endl;
    cout << "q= " << intercetta(x1, y1, m, q) << endl;
}

CodePudding user response:

This function

float coefficienteAngolare(float x1, float x2, float y1, float y2, float m) {
    return m = ((y2 - y1) / (x2 - x1));
}

has parameters passed by value. It means that it receives copies of the parameters you give. Whatever you do inside the function, cannot alter the parameters passed to it in main().

If you really want to modify m, you have to pass it by reference

float coefficienteAngolare(float x1, float x2, float y1, float y2, float& m) {
    return m = ((y2 - y1) / (x2 - x1));
}

But then, if you modify m, why do you need to return it? Most probably you either want to not return anything and just store the result in m

void coefficienteAngolare(float x1, float x2, float y1, float y2, float& m) {
    m = ((y2 - y1) / (x2 - x1));
}

//....
// in main()
coefficienteAngolare(x1, x2, y1, y2, m);
cout << "m= " << m << endl;

Or you want to return the resulting value, without passing a variable to store it.

float coefficienteAngolare(float x1, float x2, float y1, float y2) {
    return ((y2 - y1) / (x2 - x1));
}

//....
// in main()
m = coefficienteAngolare(x1, x2, y1, y2);
cout << "m= " << m << endl;

Along the same line you have to modify intercetta. Please notice that the order of the parameters is relevant. The compiler cannot guess that the q variable in main() should be the same as the q variable in intercetta, they belong to different scopes.

CodePudding user response:

The variable m (and q) in your main function are different variables than the variables in your other functions. The assignment you have after your return statement assigns a value to a variable which has its lifetime limited to the respective function's scope.

If you want to pass-by-reference, you can do this by declaring the argument as a reference:

float intercetta(float m, float x1, float y1, float& q) {
                                                // ^-------- reference
  •  Tags:  
  • c
  • Related