flag function

i try to make a program with flag. i just copy from book but not get the meaning of flag function (if i amnot mistake). i am beginer plis help me.

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
 #include <iostream>
 #include <cmath>

using namespace std;

int main(){
int a, b, c:
float D, x1, x2;
int flag;

//input koefisien
cout<<"input a :";
cin>>a;
cout<<"input b :";
cin>>b;
cout<<"input c :";
cin>>c;
cout<<endl;

//determinan
D = (b*b) - (4*a*c);

if(D>0) {
x1 = ((-b)+sqrt(D))/(2*a);
x2 = ((-b)+sqrt(D))/(2*a);
flag = 1;
}else if (D==0){
x1 = ((-b)+sqrt(D))/(2*a);
x2 = ((-b)+sqrt(D))/(2*a);
flag = 0;
}else {
flag = 0;
}

if (flag == 1) {
 cout<<"x1 = "<<x1<<endl;
 cout<<"x2 = "<<x2<<endl;
} else {
cout<<" x1 dan x2 imaginer ";
}
return 0;
}
The 'flag' simply tells you whether or not something is in a given state. It should be a boolean value.

Unfortunately, the book gave the flag variable the most unimaginative name possible, and the wrong type.

A better name would have been something like:

bool has_two_real_roots;

The function in use there is the quadratic formula. The discriminant, which is the part under the radical, calculated on line 21 of your code, tells you the following information:

    D < 0: no real roots (or solutions) to the parabola
    D = 0: one real root (parabola touches the X-axis at one point)
    D > 0: two real roots (parabola crosses the X-axis, touching it at two points)

If you admit imaginary numbers as a possible solution, then D < 0 does have a solution, but often we only want stuff in the real plane.

Notice also that the book makes an error on lines 28 and 29: since D==0, both x1 and x2 will have the same value (as there is only one root). The square root of zero is zero, so it could have been more concisely written as:

x1 = x2 = -(float)b/(2*a);

I am also unsure why a, b, and c are ints instead of floats, but...

Hope this helps.
Topic archived. No new replies allowed.