two errors which I don't know how to fix

Jun 19, 2013 at 9:50am
Hi all. On "cout << "x1 = " << x1= ((-b) - sqrt(D)/ (2*a)) << endl; cout << "x2 = " << x2= ((-b) + sqrt(D)/ (2*a)) << endl;}" lines i get errors:
invalid operands of types 'float' and '<unresolved overloaded function type>'....
How to fix them?
Thanks

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
  #include <iostream>
#include <cmath>
using namespace std;

int main(void)
{
    int a, b, c;
    float  x1, x2, x, D;
cout << "Iveskite koeficienta a: ";
cin >> a;
cout << "Iveskite koeficienta b: ";
cin >> b;
cout << "Iveskite koeficienta c: ";
cin >> c;

if (a != 0)
{
     {D=(b*b)-(4*a*c);}
     if (D>=0)
     {
     cout << "x1 = " << x1= ((-b) - sqrt(D)/ (2*a)) << endl;
     cout << "x2 = " << x2= ((-b) + sqrt(D)/ (2*a)) << endl;}

     else
     cout << "Diskriminantas neigiamas. Sprendiniu nera." << endl;}



else          if ((a == 0))
                cout << "x = " << (x = -c/b ) << endl;
                else
                cout << "Irasyk normalius skaicius, tau cia ne cirkas." <<endl;

return 0;
}
Jun 19, 2013 at 9:53am
First calculate x1 and x2, then print the results
1
2
3
4
5
6
7
   
// ...
     x1= ((-b) - sqrt(D)/ (2*a));
     x2= ((-b) + sqrt(D)/ (2*a));

     cout << "x1 = " << x1 << endl;
     cout << "x2 = " << x2 << endl;
Last edited on Jun 19, 2013 at 9:55am
Jun 19, 2013 at 9:59am
The problem is that = has higher precedence than << so the compiler will see it as
(cout << "x1 = " << x1) = (((-b) - sqrt(D)/ (2*a)) << endl);

You can use parentheses to fix it
cout << "x1 = " << (x1= ((-b) - sqrt(D)/ (2*a))) << endl;

Putting the assignment of x1 and x2 on separate lines, as Null said, is probably easier and makes the code easier to understand.
Last edited on Jun 19, 2013 at 10:02am
Jun 19, 2013 at 10:01am
Thanks :)
Jun 19, 2013 at 10:15am
By the way, this program cannot calculate correctly... Maybe you could see the problem. The main thing is that when i write, for example, a=1, b = -5, c=6, this program calculate x1= 4,5, x2 = 5,5, but x1 and x2 should be 2 and 3. What's the problem? :/
Jun 19, 2013 at 10:47am
-b will not be divided. Use parentheses to make it work.
Jun 19, 2013 at 11:47am
nah, Peter, -b works good. The main problem was, that firstly i should make
((-b) +- sqrt(D)) and only then /2*a . ;]
Jun 19, 2013 at 11:57am
That's exactly what Peter meant. He said "will not be divided".

Also, these parentheses serve no purpose, but add to the clutter: (-b)
all you need is simply
(-b - sqrt(D)) / (2*a)
Last edited on Jun 19, 2013 at 11:57am
Topic archived. No new replies allowed.