2014-09-10 2 views
0

x 패밀리의 입력을 넣으려는 코드를 시도 할 때까지 프로그램에서 각 패밀리에게 아기가 있어야합니다 (50/50의 성 중 하나를 가질 기회가 있음). 각 성별 중 하나가 성취되었습니다. 그런 다음 2, 3, 4, 5 명 또는 그 이상의 아기가있는 가족의 수와 목표를 달성하는 데 가장 많이 걸리는 아기의 수를 평균을 출력해야합니다. 나는 while 진술 (if 문 클러스터의 어딘가) 다음에 엉망이라고 믿는다. 어떤 도움이라도 대단히 감사합니다. 감사!"x"패밀리에서 아기 만들기

public class BoysAndGirls { 

    public static void main(String[] args) { 
     int families = Integer.parseInt(args[0]); 
     int boy = 0; 
     int girl = 0; 
     int fam2 = 0; 
     int fam3 = 0; 
     int fam4 = 0; 
     int fam5 = 0; 
     int total = 0; 

     for (int i = 0; i < families; i++) { 
      while ((boy <= 1) || (girl <= 1)) { 
       if (Math.random() < 0.5) { 
        boy = boy + 1; 
       } else { 
        girl = girl + 1; 
       } 
       total++; 
      } 

      if (total == 2) { 
       fam2++; 
      } 
      if (total == 3) { 
       fam3++; 
      } 
      if (total == 4) { 
       fam4++; 
      } 
      if (total >= 5) { 
       fam5++; 
      } 
     } 

     double average = total/families; 
     System.out.println("Average: " + average + " babies were had to get at least one of each sex."); 
     System.out.println("Number of families with 2 children: " + fam2); 
     System.out.println("Number of families with 3 children: " + fam3); 
     System.out.println("Number of families with 4 children: " + fam4); 
     System.out.println("Number of families with 5 or more children: " + fam5); 
     //System.out.println("The most common number of children was " + common + "."); 
    } 
} 
+0

이 숙제가 있습니까? – Zenadix

+0

@ Zenadix 예. 내가 얻을 수있는 도움을 모호하게 찾고 있습니다. 나는 도움을 받기 위해 실험실에 갈 시간을 찾지 못했습니다. –

+4

아기 만들기 = 숙제, 나는 잘못된 학위를 가지고있다 :-) – Leo

답변

2

네, 약간의 변경을해야합니다.

당신은 이제 하나의 가족에 대한 아이들의 현재 총 수를 추적 currentTotal 말을하자, 다른 변수를 가지고 있고, 모든 가족에 대한 아이들의 총 수를 추적하기 위해 다른 변수 total를 사용해야합니다.

또한 루프 시작 부분에 단일 패밀리에 대한 정보가 포함되므로 카운터 boy, girl, currentTotal을 0으로 재설정해야합니다.

결국 아이들의 평균 숫자를 계산할 때 int total에서 double까지 정수 나누기가 정확하지 않으므로 typecast이 필요합니다.

double average = total/families; 

넣어 : 코드에 적용된 모든 이러한 수정으로

double average = (double) total/families; 

, 우리가 얻을 :

대신에

public static void main(String[] args) { 

    int families = Integer.parseInt(args[0]); 
    int boy; 
    int girl; 
    int fam2 = 0; 
    int fam3 = 0; 
    int fam4 = 0; 
    int fam5 = 0; 
    int total = 0; 
    int currentTotal; 
    for (int i=0; i < families; i++){ 
     currentTotal = 0; 
     boy = 0; 
     girl = 0; 
     while ((boy < 1) || (girl < 1)){ 
      if (Math.random() < 0.5) { 
       boy = boy + 1; 
      } 
      else { 
       girl = girl + 1; 
      } 
      currentTotal++; 
      total++; 
     } 
     if (currentTotal == 2){ 
      fam2++; 
     } 
     if (currentTotal == 3){ 
      fam3++; 
     } 
     if (currentTotal == 4){ 
      fam4++; 
     } 
     if (currentTotal >= 5){ 
      fam5++; 
     } 
    } 
    double average = (double) total/families; 
    System.out.println("Average: " + average + " babies were had to get at least one of each sex."); 
    System.out.println("Number of families with 2 children: " + fam2); 
    System.out.println("Number of families with 3 children: " + fam3); 
    System.out.println("Number of families with 4 children: " + fam4); 
    System.out.println("Number of families with 5 or more children: " + fam5); 
    //System.out.println("The most common number of children was " + common + "."); 
} 

샘플 출력을 입력 10

Average: 2.7 babies were had to get at least one of each sex. 
Number of families with 2 children: 7 
Number of families with 3 children: 2 
Number of families with 4 children: 0 
Number of families with 5 or more children: 1 
01 23,516,

편집 :

아기의 가장 일반적인 수를 찾으려면, 당신은 단지 모든 fam 변수 밖으로 큰 값을 찾을 수있다. 당신은 당신 자신의 길을 할 수 있습니다, 당신을위한 제 제안은 다음과 같습니다. 크기 4의 배열을 가지고 상단에 코드를 변경 : 대신 식구들 변수 (fam2, fam3, fam4, fam5)의 각각의

int[] fams = new int[4]; 

합니다.

if(currentTotal >= 5) { 
    fams[3]++; // 5 or more children. index 3 is the 4th element 
} else { 
    fams[currentTotal - 2]++; // currentTotal - 2 because we are offsetting by 2 
} 

그런 다음 당신이 가장 큰 발견하여 가장 일반적인 요소를 찾아 낼 것입니다 :

그런 다음 루프에 상관없이 currentTotal이 무엇인지, 당신은 모든 경우를 (모든 if 문을 대체) 포함 할 수 없다 값은 fams 배열에 있습니다.

int common = 0; 
for(int i = 0; i < fams.length; i++) { 
    if(common < fams[i]) { 
     common = fams[i]; 
    } 
} 
// at this point, common would hold the most common number of kids 
+0

실제로 소년, 소녀, currentTotal 모두를 for 루프의 시작 부분에서 선언 할 수있다. –

+0

입력 해 주셔서 감사합니다. 나는 당신이 제공 한 제안을했지만 현재 사용되는 유일한 숫자는 4 또는 5 또는 그 이상입니다. 2 ~ 3 명의 자녀가 있습니다. 직접 나에게 말할 수있는 방법이 있습니까? 아니면 내 질문을 편집해야합니까? –

+0

@DarronMartinez 여기에 작업 복사본이 있습니다. http://ideone.com/CSAx3Y – nem035

0

당신은 단순히 while 루프 전에 boygirl 카운트를 재설정해야합니다. 두 번째로 for 루프를 지나면 소년과 소녀는 적어도 1 명이므로 이미 while 루프를 건너 뛰어야합니다. 당신이 total를 재설정 결코

for (int i=0; i < families; i++){ 
     boy = 0; 
     girl = 0; 
     while ((boy <= 1) || (girl <= 1)){ 
      if (Math.random() < 0.5) { 
       boy = boy + 1; 
      } else { 
       girl = girl + 1; 
      } 
     } 
     total = boy + girl; 
     ..... 
} 

그냥뿐만 아니라났습니다. 이를 수행하는 가장 좋은 방법은 루프 중에 루프를 증가시키지 말고 while 루프 이후에 boy + girl의 합계를 기반으로 간단하게 다시 할당하는 것입니다.

관련 문제