-2

I'm doing algorithm for solving Quadratic equation.

I type for A = 4, B = 10, C = 4 which gives value of 36 for delta.

My issue is that

int delta;

returns value of 35, and

double delta;

returns value of 36.

I'm using Atom text editor, rest of code is below.

#include <iostream>
#include <math.h>

using namespace std;

int main()
{
  int a,b,c;
  int delta;
  int x1, x2;
  cout << "Rownanie kwadratowe w postaci ax^2 + bx + c = 0" << endl;
  cout << "Podaj wartosc A" << endl;
  cin >> a;
  cout << "Podaj wartosc B" << endl;
  cin >> b;
  cout << "Podaj wartosc C" << endl;
  cin >> c;
  delta = pow(b,2) - (4 * a * c);
  cout << "Delta = " << delta << endl;
  return 0;
}
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
Emil
  • 1,186
  • 1
  • 8
  • 17

1 Answers1

1

It works for me. Bellow code is much shorter and better for the Minimum example, isn't it?

#include <iostream>
#include <math.h>

using namespace std;

int main()
{
  int a = 4, b = 10, c = 4;
  int delta = pow(b,2) - (4 * a * c);
  cout << "Delta = " << delta << endl;
  return 0;
}

If you use integral arithmetic then use integral not floating point operations. The problem consists of floats. Result of pow(b, 2) may be like 99.99999999997, that rounded down to int is 99.

#include <iostream>

using namespace std;

int main()
{
  int a = 4, b = 10, c = 4;
  int delta = b * b - (4 * a * c);
  cout << "Delta = " << delta << endl;
  return 0;
}
273K
  • 29,503
  • 10
  • 41
  • 64