public class numPattern {
public static void main(String[] args) {
int digit1 = 2;
int digit2 = 7;
int tal = 0;
System.out.print(digit1 + " ");
System.out.print(digit2 + " ");
while (tal < 550) {
tal = digit1 + digit2;
System.out.print(tal + " ");
digit1 = digit2;
digit2 = tal;
}
}
}
这会输出2, 7, 9, 16, 25, 41, 66......453 and 733
问题是它应该停在453,因为733超过了550。
什么命令可以确保程序在453处结束以满足大于或等于550我试图寻找?
答案 0 :(得分:3)
在tal
:
while
的值
int digit1 = 2;
int digit2 = 7;
int tal = 0;
System.out.print(digit1 + " ");
System.out.print(digit2 + " ");
while((tal = digit1 + digit2)< 550)
{
System.out.print(tal + " ");
digit1 = digit2;
digit2 = tal;
}
答案 1 :(得分:1)
只需跳过digit2
的打印输出,将tal
初始化为相同的值,然后对循环中的语句重新排序:
int digit1 = 2;
System.out.print(digit1 + " ");
int digit2 = 7;
int tal = digit2;
while (tal < 550) {
System.out.print(tal + " ");
tal = digit1 + digit2;
digit1 = digit2;
digit2 = tal;
}
答案 2 :(得分:0)
简单的改变:
while (tal < 550){
tal = digit1 + digit2;
System.out.print(tal + " ");
digit1 = digit2;
digit2 = tal;
}
为:
while (tal < 550) {
System.out.print(tal + " ");
digit1 = digit2;
digit2 = tal;
tal = digit1 + digit2;
}
和tal
的初始化:
从int tal = 0
到int tal = digit1 + digit2;
答案 3 :(得分:0)
int digit1 = 2;
System.out.print(digit1 + " "); //it will print digit1
do not print digit2
int digit2 = 7;
int tal = digit2;
while (tal < 550) {
System.out.print(tal + " ");
tal = digit1 + digit2;
digit1 = digit2;
digit2 = tal;
}
因为在循环中它首先增加值然后打印它,所以在条件为false之前它已经打印了tal = 443时的值然后它进入while循环执行总和并打印它然后去检查值
重新调整后,首先打印出值,然后执行总和,检查其是否较少,因此在443之后不会继续