Why is the program giving me a solution of -0? The program is simulating the slope formula between two points. I never had a problem like this in Java.
Here is my code:
#include <iostream>
using namespace std;
int main()
{
double x,y,xs,ys;
double slope = (ys-y)/(xs-x);
cout<<"Please input your first X coordinate with at least one trailing decimal place. \n\n";
cin>> x;
cout<<"Please input your first Y coordinate with at least one trailing decimal place. \n\n";
cin>>y;
cout<<"Please input your second X coordinate with at least one trailing decimal place. \n";
cin>>xs;
cout<<"Please input your second Y coordinate with at least one trailing decimal place. \n";
cin>>ys;
cin.get();
cout<<"Your resulting slope from the line connecting these two points is " <<slope<< ".\n";
cin.get();
return 0;
}
So they have arbitrary values and as the result value of double slope = (ys-y)/(xs-x);
can be also arbitrary. So behavior of your program is undefined.
In other words, "slope" is trying to do math on undefined variables. They are not defined until after the math is done. Put the "double slope = ....." after cin.get(); before "Your resulting....." That should make it work.
#include <iostream>
usingnamespace std;
int main()
{
double x,y,xs,ys;
double slope;
cout<<"Please input your first X coordinate with at least one trailing decimal place. \n\n";
cin>> x;
cout<<"Please input your first Y coordinate with at least one trailing decimal place. \n\n";
cin>>y;
cout<<"Please input your second X coordinate with at least one trailing decimal place. \n";
cin>>xs;
cout<<"Please input your second Y coordinate with at least one trailing decimal place. \n";
cin>>ys;
cin.get();
slope = (ys-y)/(xs-x);
cout<<"Your resulting slope from the line connecting these two points is " <<slope<< ".\n";
cin.get();
return 0;
}
In other words, "slope" is trying to do math on undefined variables. They are not defined until after the math is done. Put the "double slope = ....." after cin.get(); before "Your resulting....." That should make it work.
If the variables were undefined, it wouldn't compile. As Vlad said, they were uninitialized.