java - What's the difference when using numeric literal in termination expression of a for statement? -
why piece of code:
string value = joptionpane.showinputdialog("enter x"); //input = 100 int x = integer.parseint(value); double result = 1; (int = 1; <= x; i++) //used variable "x" here { result += (x * 1.0) / fact(i); x *= x; } public static int fact(int n) { int fact = 1; (int = 1; <= n; i++) { fact *= i; } return fact; } work differently one?
string value = joptionpane.showinputdialog("enter x"); //input = 100 int x = integer.parseint(value); double result = 1; (int = 1; <= 100; i++) //and here used value "100" { result += (x * 1.0) / fact(i); x *= x; } public static int fact(int n) { int fact = 1; (int = 1; <= n; i++) { fact *= i; } return fact; } the change made using value 100 instead of using variable x in termination expression!
when run first code, get:
9.479341033333334e7 however, second 1 get
nan why?
the difference between 2 snippets this:
for (int = 1; <= x; i++) { vs.
for (int = 1; <= 100; i++) { in first case, x gets larger every time! eventually, stop when x overflows , becomes 0, sooner in second case. explanation why results in 0 instead of other random number, see: why multiplication integer overflow result in zero?
in second case, when i = 34, fact(n) return 0, double division (0 * 1.0) /0 results in nan. double, when added nan, becomes nan, why second snippet results in nan. see: in java, nan mean?
Comments
Post a Comment