了解除数程序中的选择和循环
Understanding selections and looping in a divisor program
我的作业要求我使用定义的范围(通过输入范围内的最大数字)和用户输入的除数来查找范围内可被除数整除的所有数字,而不使用数学或除 ++、-- 或 = 之外的赋值运算符(不允许使用 +、-、/、*、%、+=、%= 等)。
使用数学运算符编写该程序非常容易,但是当我尝试仅使用递增运算符编写它时,我每次都迷路了。我对编程非常陌生。
下面是我到目前为止的代码,但它会在除数之后打印范围(1 到最大数)中的每个数字(因此,如果用户输入的除数是 5,最大数是 20,它将打印每个数字 5-20),而不仅仅是可以被除数整除的数字 (5, 10, 15, 20)。
input = new Scanner(System.in);
// input the ending number
System.out.println("Enter the ending number: ");
n = input.nextInt();
System.out.println("Enter the divisor: ");
count = input.nextInt();
variable = 0;
System.out.println("Below are all the numbers that are evenly divisible by " + count + " from 1 up to " + n);
while (count <= n){
variable++;
if (variable == count){
System.out.print(count + " ");
count++;}
循环计数那么多次,
现在下面应该可以工作,最大数量为奇数和偶数
int temp = count;
while(count<n)
{
for(int i=0; i<temp; i++)
{
variable++;
}
if(variable>n) break;
else {
count = variable;
System.out.println(count);
}
}
我的作业要求我使用定义的范围(通过输入范围内的最大数字)和用户输入的除数来查找范围内可被除数整除的所有数字,而不使用数学或除 ++、-- 或 = 之外的赋值运算符(不允许使用 +、-、/、*、%、+=、%= 等)。
使用数学运算符编写该程序非常容易,但是当我尝试仅使用递增运算符编写它时,我每次都迷路了。我对编程非常陌生。
下面是我到目前为止的代码,但它会在除数之后打印范围(1 到最大数)中的每个数字(因此,如果用户输入的除数是 5,最大数是 20,它将打印每个数字 5-20),而不仅仅是可以被除数整除的数字 (5, 10, 15, 20)。
input = new Scanner(System.in);
// input the ending number
System.out.println("Enter the ending number: ");
n = input.nextInt();
System.out.println("Enter the divisor: ");
count = input.nextInt();
variable = 0;
System.out.println("Below are all the numbers that are evenly divisible by " + count + " from 1 up to " + n);
while (count <= n){
variable++;
if (variable == count){
System.out.print(count + " ");
count++;}
循环计数那么多次, 现在下面应该可以工作,最大数量为奇数和偶数
int temp = count;
while(count<n)
{
for(int i=0; i<temp; i++)
{
variable++;
}
if(variable>n) break;
else {
count = variable;
System.out.println(count);
}
}