今天刚学while循环,听得一头雾水
老师出了道题:
山上有一口缸,能装50升水,现在里面有15升,一个人挑水一次能挑五升,多少次能挑满?
用while或do-while循环写代码
解这道题的思路在哪?
还有碰见循环的问题,怎么弄啊,觉得无处下手,很迷茫啊
帮帮忙吧
老师出了道题:
山上有一口缸,能装50升水,现在里面有15升,一个人挑水一次能挑五升,多少次能挑满?
用while或do-while循环写代码
解这道题的思路在哪?
还有碰见循环的问题,怎么弄啊,觉得无处下手,很迷茫啊
帮帮忙吧
int personCount = 0;
int sumCubage = 0;
int totalCubage = 50-15;
while(sumCubage!=35)
{
sumCubage = sumCubage+5;
personCount++;
}
System.out.println(personCount);
public static void main(String arg[]) {
int i = 15;
do {
i += 5;
System.out.println(i);
} while (i < 50);
}
}
public static void main(String[] args) {
// 缸的总容量
int total = 50;
// 缸中已有的水量
int container = 15;
// 每人每次挑的水量
int each = 5;
// 挑水的次数
int count = 0;
// 如果缸中的水比总的水量少,那说明还没有满
// 没有满的话,就继续挑水
// 如果 container 比 total 大的话,那说明不已经满出来了就不用再挑了
while(container < total) {
// 继续挑水一次,将挑水将数增加 1
count++;
// 把挑来的水倒进缸里面去,每挑一次缸中的水就增加 each 升
container += each;
// 然后再回到 while 那里继续判断是否满了,直到缸中的水满出来了
}
// 将挑水的次数输出
System.out.println(count);
}
}画了个图,看图应该会更加清晰一些 :)
Java code
public class qdb{}
学习了、、
四楼的注释超级详细 我也看懂了、、
public class Test1{
public static void main(String [] args){
int i = 15;
int count = 0;
do{
i = i + 5;
count ++;
}
while(i < 50);
System.out.println(i);
System.out.println(count);
}
}while 循环
public class Test1{
public static void main(String [] args){
int i = 15;
int count = 0;
while(i<50){
i = i + 5;
count ++;
}
System.out.println(i);
System.out.println(count);
}
}
public static void main(String[] args) {
int s = 15; 缸中已有的水量
int count = 0; // 挑水的次数
while(s <= 50){
s=s+5;
count++;
}
System.out.println(count);
}
}do-whileJava codepublic class Test01 {
public static void main(String[] args) {
int s = 15; 缸中已有的水量
int count = 0; // 挑水的次数
do {
s=s+5;
count++;
}while(s <= 50);
System.out.println(count);
}
}
public class Test11{
public static void main(String[] args){
int i = 15;//水缸里原有的15水
int count=0;//挑水次数
while(i<50){
i+=5;//一次挑5升
count++;//没挑一次水,count加1
}
System.out.println(count);
}
}循环次数固定的时候就用for,不固定时就用while;
while(i<50){
i+=5;
}
for(i=0;i<50;i=i+5){}
有区别吗?
public static void main(String [] args){
int i = 15;
int count = 0;
while(i <50){
i = i + 5;
count ++;
}
System.out.println(i);
System.out.println(count);
}
}