2015-08-09 64 views
1

所以我工作的這個問題,在用戶輸入X的個數和結果是這樣計算出0和X之間的所有數字的總和:7和倍數添加數字減去倍數

  1. 倍數11個不包括在總和中。既7和11的
  2. 但倍數被包括爲前:77

例如:

用戶輸入X >> 80

總和>>(0 + 1 + 2 + 3 + ... 77)-(7,11,14,21,22 ... ... 77)+(77)=導致

import java.util.Scanner; 
    public class testadd { 
     public static void main(String[] args) { 
      Scanner keyboard = new Scanner(System.in); 
      System.out.print("Please the number greater than 77"); 
      // int a = 0; 
      int b = keyboard.nextInt(); 
      int sum = 0; 

      int s = Math.min(0, b); 
      int e = Math.max(0, b); 

      System.out.println(s); 
      System.out.println(e); 
      int x=0; 
      for(int i=1; i<e; i++){ 
       if(i%7 ==0 || i%11 ==0){ 
        x=x+i; 
        System.out.println(x + " values of x"); 
       } 
      } 

      while (s <= e) { 
       sum += s; 
       s++; 
      } 

      System.out.print("The sum of the numbers between " + 0 + " and " + b + " is " + sum); 
     } 
    } 
+0

爲什麼你使用'Math.min'和'Math.max' ?如果'b'大於77,那麼'Math.min(0,b)'總是0,所以沒有理由使用'Math.min'使事情複雜化。類似的'Math.max',但我會讓你弄清楚'e'會被設置爲什麼。 – ajb

回答

2

你只需要一個循環來遍歷從1e的所有數字。一種優雅的方式來檢查,通過711而不是由雙方是使用^(異或)運算符整除的數字:

long sum = 0; 
for (int i = 1; i <= e; ++i) { 
    if (!((i % 7 == 0)^(i % 11 == 0))) { 
     sum += i; 
    } 
} 
2

您還沒有包括數整除77的小號嗯。你的for循環應該是這樣的(你不需要while循環):

 for (int i=1; i<e; i++) { 
      if((i%77 == 0) || (i%7 !=0 && i%11 !=0)) { 
       x=x+i; 
       System.out.println(x + " values of x"); 
      } 
     } 

即添加i總如果任i是77或i整除是整除711