这是我目前坚持的一项任务。
问题是“使用do..while循环以相反顺序打印因子“ n””
此操作的序言允许用户输入任何int值,并首先通过标准if语句查找非因数,然后使用DO循环按降序查找和打印因数。我坚持的事实是,如果不使用数组或其他IF循环,就无法决定如何在DO循环中求值。任何帮助表示赞赏。我将在底部标记代码。 (这不是很漂亮,因为它只是程序的草稿,并且尚未清除。)
import java.util.Scanner;
public class NestedFactorLoop
{
public static void main(String [] args) //entry point
{
Scanner keyboard = new Scanner(System.in);
int choice = 0, i = 1, average = 0, nonFactorCounter = 0;
System.out.print("Enter a positive integer: ");
choice = keyboard.nextInt();
System.out.println("\na. Use a for loop to print non-factors of 26: \n");
while(choice > i){
if( choice % i != 0){
System.out.print( i + " ");
nonFactorCounter++;
average += i;
}
i++;
}
System.out.println("\n\nNumber of non-factors: " + nonFactorCounter);
System.out.printf("Average value of non-factors: %-4.2f", (double)(average / nonFactorCounter), " ");
System.out.println("\n\nb. Use a do..while loop to print factors of 26 in reverse order:\n");
######################################DO loop section
i = choice;
do {
System.out.print(i + " ");
i--;
}while( i > 0 );
####################################
System.out.println("\n\nNumber of factors: ");
System.out.println("Average value of factors: ");
}
}
最佳答案
do...while
在每种方式上均与while
循环相同,不同之处在于它保证内部的代码块至少执行一次。因此,可以使用do...while
循环来实现它,就像使用while
循环一样。
choice = i;
average = 0;
int factorCounter = 0;
do {
if (choice % i == 0) {
System.out.print(i + " ");
factorCounter++;
average += i;
}
i--;
} while (i >= 1);
System.out.println("\n\nNumber of factors: " + factorCounter);
System.out.printf("Average value of factors: %-4.2f", (double) (average / factorCounter), " ");
关于java - 使用do .. while循环以降序打印因数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61670077/