Type mismatch: cannot convert from double to integer in eclipse

426 views Asked by At

The compiler reports the line with the call to Math.pow() as an error. I'm making a program that computes the solution to a quadratic by using the quadratic formula with inputted variables for class. Arrow for convenience

import java.util.*;
public class QuadraticFormula {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a: ");
        int a = input.nextInt();
        System.out.println("Enter b: ");
        int b = input.nextInt();
        System.out.println("Enter c: ");
        int c = input.nextInt();

    →   int discriminant = (Math.pow(b, 2) - 4*a*c);

        input.close();

    }

}

1

There are 1 answers

0
eattrig On BEST ANSWER

Cast it as an int:

int discriminant = (int)(Math.pow(b, 2) - 4*a*c);

This is because Math.pow() expects 2 doubles and returns a double. So the Runtime will up-cast b and 2 from int to double then return a double. Then it will up-cast 4, a, and c to doubles. The result is a double. It must be cast back down to int. This is safe in this case because we know all input values are ints.