math - I am getting NaN for an answer to my quadratic equation calculator- JAVA -


this main class:

import java.util.scanner;  public class calc { public static void main(string[] args){     scanner variablea = new scanner(system.in);     scanner variableb = new scanner(system.in);     scanner variablec = new scanner(system.in);     int a1, b1, c1;     system.out.println("enter 'a' variable");     a1 = variablea.nextint();     system.out.println("enter 'b' variable");     b1 = variableb.nextint();     system.out.println("enter 'c' variable");     c1 = variablec.nextint();      algorithm algorithmobject = new algorithm();     algorithmobject.algorithm(a1, b1, c1);  }  } 

and second one

      public class algorithm{ public void algorithm(int a, int b, int c){     double x1;     double square = math.sqrt(b*b - 4*a*c);     double numerator = b*-1 + square;     double finalanswer = numerator/2*a;      system.out.println(finalanswer); } 

}

eclipse doesn't give me errors, after asks 3 variables , enter them, gives nan. idea have done wrong?

there issues code culprit line:

double square = math.sqrt(b*b - 4*a*c); 

if b*b - 4*a*c negative (there no solution equation) square nan , every computation involving nan well. can check here.


you improve calculator first checking if b*b - 4*a*c < 0 , if write console there no real solution (and of course stop computations there).


i change public void algorithm(int a, int b, int c)

public void algorithm(double a, double b, double c) 

integer arithmetic can surprise when least expect , see no reason why a, b , c should constrained int-s.


ok, hope helped.


Comments

Popular posts from this blog

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -