栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

day09

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

day09

Day09 —— While 循环 1. Background

今天是学习java的第9天了,今天学习的内容是while循环。

在我的心里面while循环是比for循环更加简单的存在,一直是把它当作for的下位替代来的。记得我三年前刚学C语言的时候,就只会一个while循环,然后用while循环实现了冒泡排序等等简单排序。可是之后学完for循环之后,写程序几乎没有用过while了,因为for属实好用。

2. Description

今天的代码是用while循环求和,但是Sum不能超过一个最大值,其中求和的value每次自增1.

代码比较简单,整体和C语言相似,所以就直接上代码了。

3.Code
package basic;



public class Day09 {
    
    public static void main(String[] args) {
        whileStatementTest();
    } // Of main

    
    public static void whileStatementTest() {
        int tempValue = 0;
        int tempSum = 0;
        int tempMax = 100;

        // Approach 1.
        while (tempSum <= tempMax) {
            tempValue++;
            tempSum += tempValue;
            System.out.println("tempvalue = " + tempValue + " , tempSum = " + tempSum);
        } // Of while
        tempSum -= tempValue; // 当tempSum大于tempMax时才会跳出循环,与所求不符,故减去最后的加的那个tempValue.
        
        System.out.println("The sum not exceeding " + tempMax +" is: " + tempSum);

        // Approach 2.
        tempSum = 0;
        tempValue = 0; // 此处展示第二种求值方法,为避免上面代码对变量的污染,此处重新初始化变量

        while (true) {
            if (tempSum > tempMax) {
                break;
            } // Of if
            
            tempValue++;
            tempSum += tempValue;
            System.err.println("tempvalue = " + tempValue + " , tempSum = " + tempSum);
        } // Of while
        tempSum -= tempValue;

        System.out.println("The sum not exceeding " + tempMax +" is: " + tempSum);
    } // Of whileStatementTest
} // Of Day09

运行结果:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/737914.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号