"stupid" c++

I wrote simple program (it's simple version of me last home work) and i dont understand why it dont show ERROR when X=2 and where line with X=3 disapears.

Is it posible to limit real number to format 12345.67 (2 digitals after point ) ?
P.s. why 2-2=2,2*10^-16 instead of 0

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <cstdlib>
using namespace std;
//------------
int main()
{

double C = 2.0;
double Ab = 1.0; //interval [Ab;Ae] begins
double Ae = 3.0; //interval [Ab;Ae] ends
double As=0.10; //interval [Ab;Ae] step, works: 1, 2, 0.25, 0.5 ; dont work: 0.2, 0.1
double t; 
//cout << "write interval step " << endl;
//cin >> As;

for( double x = Ab; x <= Ae; x += As)
{
cout << "c= " << C << " | x= " << x;
t=x-C;
cout <<" | t=c-x= "<<t<<endl;

if( t != 0)
{
double y = 1 / (C - x);
cout << "Y = 1/t= " << y << endl<< endl;
}
else
{cout << "ERROR. dvision from 0 imposible. "<< endl<< endl;}
}




cout <<"\n\n\n while.................\n";

double xx=Ab;
while (xx<=Ae)
{
cout << "c= " << C << " | xx= " << xx;
t=C-xx;
cout <<" | t=c-xx= "<<t<<endl;

if( t != 0)
{
double y = 1 / (C - xx);
cout << "Y = 1/t= " << y << endl<< endl;
}
else
{cout << "ERROR. dvision from 0 imposible. "<< endl<< endl;}
xx+=As;
}


system ("pause");
return 0;
}
Last edited on
any answers?
Well, for one thing:
You're error-checking for t = x-C != 0, but dividing by C-x. Deduction is not commutative. You did it right the second time around.

To change the output precision (only output! not internal!), use this:
http://www.cplusplus.com/reference/iostream/ios_base/precision/

Floating point math is imperfect. However, for most applications, it is more than precise enough. The output can simply be confusing. Just keep in mind that when dealing with deductions and comparing the result to zero, you might want to compare to an insignificantly small number instead. I use:
#define zero 0.000001
Change it according to your own precision requirements.
Topic archived. No new replies allowed.