Simple program giving solution of -0?

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;
}
You did not initialize variables

double x,y,xs,ys;

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace 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;
}
Last edited on
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.

program is working fine now, thanks guys.
Topic archived. No new replies allowed.