import java.util.Scanner;
public class Loop1 {
public static void main(String[] args) throws Exception {
Loop1 l1 = new Loop1();
l1.scannerNumber();
}
public void scannerNumber() {
Scanner scan = new Scanner(System.in);
System.out.println("Введите число: ");
long x = 0;
long result = 1;
int x1 = 0;
int x2 = 0;
while (x1 == 0 || x1 <0) {
try {
if (x2 == 5) {
System.out.println("Слишком много попыток. Программа закрывается");
System.exit(0);
}
x = Long.parseLong(scan.nextLine());
x1++;
if (x<0) {
System.out.println("Вы ввели отрицательное число");
x1--;
x2++;
}
} catch (Exception e) {
System.out.println("Повтори попытку: ");
x2++;
}
}
if (x == 0) {
System.out.println("Result = " + result);
return;
}
for (int i = 0; i < x; i++) {
if (result < 0) {
System.out.println("У вас получилось переполнение " + result);
break;
} else if (result > 0){
System.out.println("Result = " + result);
result *= (x - i);
}
}
}
}
Math.rint返回最接近的整数值,但类型是保留的
double。这避免了将大值转换为整数类型时的溢出问题:从键盘输入小数时,必须输入逗号,而不是句点。
最简单的选择是丢弃小数部分(自定义为long),然后检查原始数字与没有小数部分的数字之间的差是否大于0
上面的例子会说数字 3.00 是一个整数(这是正确的)