gpt4 book ai didi

java - 我无法将整数放入范围循环中

转载 作者:行者123 更新时间:2023-12-01 18:40:31 24 4
gpt4 key购买 nike

我一直在尝试编写一个程序来计算 1 到 10 之间的数字的阶乘。我可以让它正确计算阶乘,但问题是,即使数字大于 10 或小于 10,它也会计算阶乘1 不再询问。

import java.util.Scanner;

public class Factorial {


public static void main (String[] args){

Scanner input = new Scanner(System.in);

int num ;
int factorial = 1;


do{
System.out.println("Enter an integer(1-10) :");
num = input.nextInt();
}while(num>10 && num<1);


for (int x = 1 ; x <= num ; x++)
factorial = factorial * x;




System.out.println("Factorial of number is " + factorial);



}
}

在将变量“num”声明为随机数字后,我尝试使用 while 而不是 do-while 。但随后它给了我该随机数的阶乘。这段代码有什么问题?

最佳答案

您的 while 循环条件不正确。它不能同时大于 10 且小于 1。使用逻辑或运算符 || 来强制范围:

}while(num > 10 || num < 1);

关于java - 我无法将整数放入范围循环中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20085428/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com