user8697707 user8697707 - 3 years ago 123
Java Question

Is this the correct expected output of program?

I need help determining if this is the right output of the problem below. I wrote what I think to be correct but I would like some verification. First time posting here so I apologize if I did anything incorrectly.

Mexico's population is 62 million and is growing at the annual
rate of 7%. The United States' current population is 280 million and is
growing at the annual rate of 2%. If these two countries were to
maintain their current rates of growth, in how many years will Mexico's
population be more than half that of the United States? Your program
should answer this question.

This is what I wrote

public class Population
{
public static void main(String[] args)
{
int year = 0;

int mexicoPop = 62000000;
double mexRate = mexicoPop * .07;

int usPop = 280000000;
double usRate = usPop * .02;

int usHalf = 140000000;
for(int i=mexicoPop; i<=usHalf; i++)
{
mexicoPop += mexRate;
usPop += usRate;
usHalf = usPop/2;
year++;
}
System.out.println("Mexico's population will be more than half of the US in " + year + " years");

}
}


I get an output of 1011741824 but have no idea if that's actually the correct number given the math problem. If I knew the number it would be a lot easier to tell if my program is correct. Can anyone assist with this. Thank you in advance for your time.

Answer Source

Mathematically you'll have to do something like this for the years until

Mexico's population be more than half that of the United States?

int numberOfYears = 0;
while(mexicoPop < usPop / 2)
{
    mexicoPop = mexicoPop + mexicoPop * .07; // since the RHS would be changing every year
    usPop = usPop + usPop * .02;    
    numberOfYears++; 
}
System.out.println(numberOfYears);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download