2014-01-24 5 views
0

기본적으로 20 개의 양 그룹이 있습니다. 80 마리의 양으로 성장한 후에는 더 이상 감독 할 필요가 없습니다. 양, N, 매년 t의 수는, 발견된다for Loop in Java - 지수

N = 220/(1 + 10 (0.83)^t)

이 프로그램은 양이 몇 년 찾아 시도 감독을 받고 0에서 시작하여 25까지 올라가는 t에 대해 N의 값을 씁니다.

이것은 지금까지 제 코드입니다 ... 작동하지 않는 것 같아요. 힘에 곱하는 부분. 루프의 각 반복에서 0.83을 곱한 변수 "power"를 사용하려고합니다. 도움이된다면 고맙습니다.

public static void main(String[] args) { 

    System.out.println("A breeding group of 20 bighorn sheep is released in a protected area in Colorado."); 
    System.out.println("After the group has reached a size of 80 sheep, the group does not need to be supervised anymore."); 
    System.out.println("This program calculates how many years the sheep have to be supervised."); 
    int number = 20; 
    int power = 1; 
    for(int years = 0; number < 80; power*= 0.83) { 
     number = 220/(1 + 10 * power);   
     System.out.println("After " + years + " years, the number of sheep is: " + number); 
     years++; 
    } 
} 
} 
+5

'double'을 사용해야하는 경우 모든 계산을 정수로 수행합니다. 처음'power * = 0.83'을 실행하면'power'의 값은 0이됩니다. –

+2

정확하게 그것이 작동하지 않는 것 같습니다. – fedorSmirnov

+1

[Math.pow (double, double)] (http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#pow%28double,%20double%29)를 사용합니다. . –

답변

2

데이터 유형을 정수에서 정수로 변경하십시오. 나는 그것을 시도하고 올바르게 실행됩니다. 또한 < 80이 아닌 < 년 동안 실행되도록 for 루프를 수정하고자 할 수 있습니다. 숫자는 청결을 위해 루프 내부의 로컬 변수로 만듭니다.

public static void main(String[] args) { 
    System.out.println("A breeding group of 20 bighorn sheep is released in a protected area in Colorado."); 
    System.out.println("After the group has reached a size of 80 sheep, the group does not need to be supervised anymore."); 
    System.out.println("This program calculates how many years the sheep have to be supervised."); 
    double power = 1; 
    boolean foundFirstOverEighty = false; 
    for (int years = 0; years < 25; years++) { 
     double number = 220/(1 + 10 * power); 
     System.out.println("After " + years + " years, the number of sheep is: " + number); 

     if (!foundFirstOverEighty && number >= 80) { 
      System.out.println("First time number of sheep exceeded eighty. " + years + " years. number of sheep is: " + number); 
      foundFirstOverEighty = true; 
     } 

     power *= 0.83; 
    } 
} 
+0

많은 도움을 주신 고마워요.하지만 양이 처음 80 세가되었을 때 정확한 해를 어떻게 추출 할 수 있을지 궁금합니다. – Freedom

+1

:) 처음으로 80 점을 확인했습니다. – user2684301

+0

thx : D !!!!!!!! – Freedom