【发布时间】:2019-04-14 22:40:02
【问题描述】:
我正在为一项作业处理 Java 循环。我必须编写一个循环,从三个国家的人口开始,提高/降低每个国家,直到一个国家低于其他两个,然后打印人口,以及达到该结果所需的年数。
我使用了两个带有正确代码的条件,但是当条件正确时,它们就不能正常工作。循环必须一直运行,直到墨西哥和日本人口高于美国人口,所以这就是我正在使用的:
如果我使用此条件 - mexpop > usapop && jappop > usapop,则循环不会运行,因为 USA 已经高于墨西哥和日本(315,000,000 对 121,000,000 和 127,000,000)。
如果我使用这个条件 - mexpop
我尝试的最后一个选项是:usapop
预期的输出应该很明显,但这是我得到的:
墨西哥人口为 273,286,490。美国人口为 278,014,339。日本人口为 278,115,163。这一变化历时 78 年。
我认为日本流行音乐更高是完全幸运的,但即使我使用逻辑 AND 运算符,它似乎也不符合这两个条件。
/* Import Java utilities required for the program. */
import java.text.DecimalFormat;
class Population_for {
public static void main(String[] args) {
/** Declare variables that will be used in the program. **/
double usapop, mexpop, jappop;
int years;
/** This is the start of the for loop.
* The first line declares the variables (mexpop, usapop, jappop), the second line declares the conditions (mexpop less than**/
for(mexpop=121000000, usapop=315000000, jappop=127000000, years=1; mexpop < usapop && jappop < usapop; years++){
mexpop = mexpop * 1.0105;
usapop = usapop * 0.9984;
jappop = jappop * 1.0101;
DecimalFormat df = new DecimalFormat("###,###,###");
System.out.println("The Mexican population is "+(df.format(mexpop))+". The United States population is "+(df.format(usapop))+". The Japanese population is "+(df.format(jappop))+". This change took "+years+" year(s).");
System.out.println("");
}
}
}```
【问题讨论】:
标签: java loops for-loop math while-loop