2017-10-16 78 views
0

編寫接受來自用戶的開始號碼和結束號碼的程序。對於該範圍內的每個數字,它將打印均勻分割的所有數字(除此之外還有0個餘數)。用於循環打印的均勻分割數給定範圍

我一直只能得到範圍內的第一個數字,但它不會打印正在進行的和最終的數字。示例輸入只是:85 89.輸出應該是這樣的:

85是由1 5 17 85

86整除是由1 2 43 86

87整除是整除通過1 3 29 87

88是由1 2 4 11 22 44 88

89整除由1 89

import java.util.*; 
public class NumberRange { 
public static void main(String args[]) { 
    Scanner in = new Scanner(System.in); 
    int num1; 
    int num2; 
    num1 = in.nextInt(); 
    num2 = in.nextInt(); 
    System.out.print(num1 + " is evenly divisible by "); 
    for(num2 = 1; num2 <= num1; num2 ++) 
     { 
     if (num1 % num2 == 0) 
     { 
      System.out.print(num2 + " "); 
     } 
     } 
} 
} 
整除
+0

您的輸入是什麼? –

回答

0

您的意見顯示此不變:num1 <= num2。因此,而不是與for (num2 = 1; num2 <= num1; num2 ++)丟棄num2輸入,你想要的外環:

for (int n = num1; n <= num2; n++) 

它要麼調用一個輔助函數(包含循環),或至少要求從1運行嵌套循環.. n ,測試剩下的東西。如果將內部循環放入適當命名的輔助函數中,您的老師會留下深刻的印象。提示:您需要爲該內部循環聲明另一個變量。

0
/* package whatever; // don't place package name! */ 

import java.util.*; 
import java.lang.*; 
import java.io.*; 

/* Name of the class has to be "Main" only if the class is public. */ 
class Ideone 
{ 
    public static void main (String[] args) throws java.lang.Exception 
    { 
     Scanner in = new Scanner(System.in); 
     int num1; 
     int num2; 
     num1 = in.nextInt(); 
     num2 = in.nextInt(); 

     for(int i = num1; i <= num2; i++) 
     { 
      System.out.print(i + " is evenly divisible by "); 
      for(int j = 1; j <= i; j++) 
      { 
       if (i % j == 0) 
       { 
         System.out.print(j + " "); 
       } 
      } 
      System.out.println(); 
     } 
    } 
}