0
votes

I need to find the square roots of a quadratic equation: ax^2+bx+c=0.

let h a b c = 
  if (b*b-4*a*c) < 0 then begin 
    print_string "There are no real solutions" 
  end
  else if (b*b-4*a*c) = 0 then begin
    print_string "The equation has 1 solution x_1=";
    print_int ((-b)/(2*a));
  end
  else begin
    float_of_int a;
    float_of_int b;
    float_of_int c;
    print_float (((-.b)+.sqrt(b*.b-.4.*.a*.c))/.(2.*.a)); 
    print_float (((-.b)-.sqrt(b*.b-.4.*.a*.c))/.(2.*.a))
  end;;

Why this code gives me syntax error here saying that "This expression has type int but an expression was expected of type float":

begin
  float_of_int a;
  float_of_int b;
  float_of_int c;
  print_float (((-.b)+.sqrt(b*.b-.4.*.a*.c))/.(2.*.a)); 
  print_float (((-.b)-.sqrt(b*.b-.4.*.a*.c))/.(2.*.a))
end;;

Also is there any other easier way to solve this problem?

1

1 Answers

2
votes

So, I edited your question because it was unreadable, try to format it like this in the future ;-)

For the answer, here's your problem : OCaml is a functional language so when you write float_of_int a it doesn't change a (you should have had a warning saying that this expression returns something but you don't handle it). The type of float_of_int is int -> float so you give it an integer and it gives you back a float that you need to store in a variable.

What you should write is then :

begin
  let a = float_of_int a in
  let b = float_of_int b in
  let c = float_of_int c in
  print_float (((-.b)+.sqrt(b*.b-.4.*.a*.c))/.(2.*.a)); 
  print_float (((-.b)-.sqrt(b*.b-.4.*.a*.c))/.(2.*.a))
end;;

Side note : I don't know why you don't cast it as a float in the second branch since -b/2a is not necessarily an integer


And as another side note, since you use b*b - 4*a*c four times, put it in the variable in the beginning : let delta = b*b - 4*a*c in ...