Need some help with a mathematic function

Hello i am trying to write my first "mostly" unassisted and copy pasted program but i am having some issues i have the following function but it obviously breaks when the user inputs values that would cause divide by zero

void func1 (float YA, float YB, float XA, float XB, float& top, float& bot, float& slope)
{
top = YA-YB;
bot = XA-XB;
slope = top/bot;

}


i had tried editing and if statement in like so

void func1 (float YA, float YB, float XA, float XB, float& top, float& bot, float& slope)
{
top = YA-YB;
bot = XA-XB;
if (bot=0)
{
cout << "slope is undefined";
}
else
{
slope = top/bot;
}

}

but then no matter what value you input the output value is 1.#inf just looking for how i would go about doing this/if im evel close to the right track
change if(bot=0) to if(bot==0)

= is for assignment, == is for comparison
i tried your suggested solution the program output a crazy scientific expression instead of stopping and outputting undefined slope
What numbers are you entering into it? The scientific expression might be the correct answer if the bottom is not equal to 0. You can put cout << fixed << 'variable', to make sure it's shown in decimal form.
yes i know the answer should have been 1.5 i input YA=6 XA=6 YB=4 XB=3 and would output that but i was able to fix it after thinking about what branflake explained to me here is my end program (yes i know there is prolly 300things i could do better)

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

long func1 (float YA, float YB, float XA, float XB, float& top, float& bot, float& slope)
{
top = YA-YB;
bot = XA-XB;
while (bot==0)
{
cout << "Slope is undefined" << endl;

system("pause");

return 0;
}
slope = top/bot;
}

int main ()
{
float XA;
float XB;
float YA;

float YB;
float X;
float Y;
float Z;
cout << "Enter X 1 >";
cin >> XA;
cout << "Enter Y 1 >";
cin >> YA;
cout << "Enter X 2 >";
cin >> XB;
cout << "Enter Y 2 >";
cin >> YB;
func1 (YA, YB, XA, XB, X, Y, Z);
if (Y==0)
{
return 0;
}
else
{
cout << "The slope of the line between your two points is > " << Z << endl;
}

system("PAUSE");

return 0;
}

Such as i adjusted the if then statement to output my slope is undefined vs the while statement
Last edited on
Topic archived. No new replies allowed.