C#學習筆記(五):while循環和for循環


while循環

while循環和for循環,可以相互替換,范圍和效能一樣,理解事物的邏輯不一樣
while循環用於條件不確定的邏輯
for循環用於計算次數的邏輯

for循環

快捷寫法,按兩下TAB
i++:for+按兩下TAB
i--:forr+按兩下TAB
for循環:鎖死次數
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace w2d1_for
{
    class Program
    {
        static void Main(string[] args)
        {
            #region for循環
            //for循環經常用來做固定次數,或者是在固定區間的循環
            //如:寫一百遍“我要學好C#”
            //while循環經常來做,某一條件或者多條件達成則終止的循環
            //如:直到密碼正確才允許登錄
            //for (第一表達式(初始表達式);第二表達式(條件表達式);第三表達式(增量表達式))
            //{
            //循環體
            //}
            //在for循環開始之初,會執行初始表達式一次
            //在循環體開始前會執行條件表達式
            //如果條件表達式為真,則執行循環體完成后,執行增量表達式,再問條件表達式,以此循環
            //否則結束循環
            //正增長循環,快捷鍵:for +兩下TAB;
            for (int i = 5; i <= 500; i++)//循環次數500-5+1=496
            {
            }
            //負增長循環,快捷鍵:forr + 兩下TAB;
            for (int i = 500 - 1; i >= 0; i--)
            {
            }
            #endregion
            #region for循環練習
            //找出100內所有素數。素數/質數:只能被1和這個數字本身整除的數字,1不是質數, 最小的質數是2。
            //如果你遇到一個復雜,要抽象其子問題
            //子問題:某一個數是不是質數
            for (int j = 2; j <= 100; j++)
            {
                int num = j;
                for (int i = 2; i <= num; i++)
                {
                    if (i == num)
                    {
                        Console.WriteLine("{0}是一個質數", i);
                        break;
                    }
                    if (num % i == 0)
                    {
                        //Console.WriteLine("{0}不是一個質數", i);
                        break;
                    }
                }
            }
            //求100-999之間的水仙花數,例如:153 = 1*1*1+5*5*5+3*3*3
            //取某一位等於這個數 余這個位的上一位,如取百位,余千,然后與本位相除,如百位,除一百
            //abc = a * a * a + b * b * b + c * c * c;
            for (int i = 100; i <= 999; i++)
            {
                int a = (i % 1000) / 100;
                int b = (i % 100) / 10;
                int c = (i % 10) / 1;
                if (i == a * a * a + b * b * b + c * c * c)
                {
                    Console.WriteLine(i);
                }
            }
            #endregion
            #region 循環小練習
            //求1-100之間所有偶數的和?
            int count = 1;
            int sum = 0;
            for (int i = 1; i <= 100; i++)
            {
                if (count % 2 == 0)
                {
                    sum += count;
                }
                count++;
            }
            Console.WriteLine(sum);
            //求數列  1,1,2,3,5,8,13, ... 的第20位數字是多少?
            int count1 = 1;
            Console.WriteLine(count1);
            int count2 = 1;
            Console.WriteLine(count2);
            int count3 = count1 + count2;
            for (int i = 3; i <= 20; i++)
            {
                count1 = count2;
                count2 = count3;
                count3 = count1 + count2;
                Console.WriteLine(count3);
            }
            //假如火星2016年培養學員10萬人,每年增長80%,請問按此速度增長,
            //到哪一年培訓的學員人數將達到100萬人?
            int year = 2016;
            float stu = 10f;
            float rate = 0.8f;
            while (true)
            {
                year++;
                stu += stu * rate;
                if (stu >= 100f)
                {
                    Console.WriteLine("{0}年培訓的學員人數將達到100萬人", year); break;
                }
            }
            //輸入班級人數,然后依次輸入學員成績(需提示當前是第幾個學員),計算班
            //級學員的平均成績和總成績。
            Console.WriteLine("輸入班級人數");
            int num = int.Parse(Console.ReadLine());
            float score = 0;
            float sum = 0;
            float aver = 0;
            bool isInputOk = false;
            for (int i = 1; i < num; i++)
            {
                Console.WriteLine("請輸入第{0}位同學的成績", i);
                score = float.Parse(Console.ReadLine());
                sum += score;
                Console.WriteLine("是否繼續輸入(y/n)");
                while (true)
                {
                    string j = Console.ReadLine();
                    if (j == "y")
                    {
                        break;
                    }
                    else if (j == "n")
                    {
                        isInputOk = true; break;
                    }
                    else
                    {
                        Console.WriteLine("輸入有誤,請重新輸入");
                    }
                }
                if (isInputOk)
                {
                    break;
                }
            }
            aver = sum / num;
            Console.WriteLine("班級學員的平均成績為{0},總成績為{1}", aver, sum);
            //老師問學生,這道題你會作了嗎?如果學生答“會了(y)”,則可以放學,
            //如果學生不會做(n),則老師再講一遍,再問學生是否會做了。。。
            //直到學生會了為止,才可以放學
            //直到學生會了或老師給他講了10遍還不會,都要放學
            bool ok = false;
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("老師問:這道題你會作了嗎?");
                Console.WriteLine("學生答:會了/不會做(y/n)");
                while (true)
                {
                    string ansanswer = Console.ReadLine();
                    if (ansanswer == "y")
                    {
                        Console.WriteLine("你真聰明"); ok = true; break;
                    }
                    else if (ansanswer == "n")
                    {
                        Console.WriteLine("老師又講了一遍"); break;
                    }
                    else
                    {
                        Console.WriteLine("輸入有誤,請重新輸入");
                    }
                }
                if (ok)
                {
                    break;
                }
            }
            Console.WriteLine("放學了");
            //在控制台上輸出如下10 * 10的空心星型方陣
            //********** 畫10個點*
            //*        * 畫第1個是*,畫第10個是*,其他是空格
            //*        *
            //*        *
            //*        *
            //*        *
            //*        *
            //*        *
            //*        *
            //**********
            //1、把問題圖形化,直觀看到問題的點
            //2、在圖形化的問題中找規律,找子問題
            //子問題:畫出每一行,畫出一行,畫出一個*
            //羅列出所有可能性,在不同可能性中找規律
            //3、把子問題拼合
            //**********
            //**********
            //**********
            //**********
            //**********
            //**********
            //**********
            //**********
            //**********
            //**********
            //方法一:
            for (int j = 0; j < 10; j++)
            {
                #region 子問題1
                if (j == 0 || j == 9)
                {
                    #region 子問題2
                    for (int i = 0; i < 10; i++)
                    {
                        #region 子問題3
                        Console.Write("*");//按位輸出
                        #endregion
                    }
                    #endregion
                }
                else
                {
                    for (int i = 0; i < 10; i++)
                    {
                        if (i == 0 || i == 9)
                        {
                            Console.Write("*");
                        }
                        else
                        {
                            Console.Write(" ");
                        }
                    }
                }
                #endregion
                Console.WriteLine();//換行
            }
            //方法二:優化
            for (int i = 0; i < 10; i++)
            {
                for (int j = 0; j < 10; j++)
                {
                    if (i == 0 || i == 9 || j == 0 || j == 9)
                    {
                        Console.Write("*");
                    }
                    else
                    {
                        Console.Write(" ");
                    }
                }
                Console.WriteLine();
            }
            //在控制台上輸出如下10 * 10的三角形方陣
            for (int i = 0; i < 10; i++)
            {
                for (int j = 0; j < 10; j++)
                {
                    if (j <= i)
                    {
                        Console.Write("*");
                    }
                    else
                    {
                        Console.Write(" ");
                    }
                }
                Console.WriteLine();
            }
            //在控制台上輸出如下10行的金字塔方陣
            //                              
            //            *             
            //           ***                
            //          *****             
            //         *******
            //        *********
            //       ***********
            //      *************
            //     ***************
            //    *****************
            //   *******************   
            //n   2n-1 m-n m
            //行n 星數 空格 總行數m
            //1   1    9   10
            //2   3    8   10
            //3   5    7   10
            //4   7    6   10
            //我的練習
            int a = 9;
            for (int i = 0; i < 10; i++)
            {
                for (int j = 0; j < 20; j++)
                {
                    if (j >= (10 - i))
                    {
                        Console.Write("*");
                        if (j > a)
                        {
                            break;
                        }
                    }
                    else
                    {
                        Console.Write(" ");
                    }
                }
                a++;
                Console.WriteLine();
            }
            //老師示范
            int m = 10;
            for (int j = 1; j <= 10; j++)
            {
                int n = j;
                int start = 2 * n - 1;
                int space = m - n;
                for (int i = 0; i < space; i++)
                {
                    Console.Write(" ");
                }
                for (int i = 0; i < start; i++)
                {
                    Console.Write("*");
                }
                Console.WriteLine();
            }
            //空心金字塔
            int m = 10;
            for (int j = 1; j <= 10; j++)
            {
                int n = j;
                int start = 2 * n - 1;
                int space = m - n;
                for (int i = 0; i < space; i++)
                {
                    Console.Write(" ");
                }
                for (int i = 0; i < start; i++)
                {
                    if (j == m)
                    {
                        Console.Write("*");//讓最后一行輸出星號
                    }
                    else
                    {
                        if (i == 0 || i == start - 1)
                        {
                            Console.Write("*");
                        }
                        else
                        {
                            Console.Write(" ");
                        }
                    }
                }
                Console.WriteLine();
            }
            #endregion
        }
    }
}

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace w2d1_while_for
{
    class Program
    {
        static void Main(string[] args)
        {
            #region while循環
            //while循環是詢問條件是否達成,然后決定是否執行代碼塊(循環體)
            //執行完成之后再次詢問條件,以此循環,只到條件不滿足為止
            //如果你的條件在循環體中沒有變化,這個循環就是死循環
            //循環能否跳出:1、條件需要在循環體內變化,2、無盡的趨向條件的邊界(等同for循環、遞歸)
            //打豆豆,當豆豆血量高於50的時候,他會說沒吐,小於50時,他會說:別打了,吐了
            //用while循環打到豆豆吐為止
            int health = 100;
            while (health > 50)//布爾表達式(條件)
            {
                Console.WriteLine("你暴打了一頓豆豆,然后問他:吐嗎?");
                health -= 10;//條件變換
                if (health > 50)
                {
                    Console.WriteLine("不吐");
                }
                else
                {
                    Console.WriteLine("別打了,吐了,吐了");
                }
                Console.ReadKey(true);
            }
            //向控制台輸出100遍“我要學好C#,然后學好Unity”
            //如果符號是>和<,初始量-邊界量,邊界量-初始量
            //如果符號是>=和<=,初始量-邊界量+1,邊界量-初始量+1
            //如果符號是>=和<=,表示你的循環范圍 從 初始量 到 邊界量
            int count = 1;
            while (count <= 100)
            {
                Console.WriteLine("“我要學好C#,然后學好Unity。”第{0}遍", count);
                count++;
            }
            //向控制台輸出1到100之間的偶數
            int count = 1;
            while (count <= 100)
            {
                if (count % 2 == 0)
                {
                    Console.WriteLine(count);
                }
                count++;
            }
            //向控制台輸出1到100之間所有整數的和
            int count = 1;
            int sum = 0;
            while (count <= 100)
            {
                sum += count;
                count++;//變換量 盡可能是放在處理過程之后
            }
            Console.WriteLine(sum);
            #endregion
            #region break方法
            //思考題
            //一只蝸牛在井底,井深30米,蝸牛每天爬3米,晚上滑2米,請問蝸牛要爬多少天,才能爬出井口
            int climb = 0;
            int sum = 0;
            int day = 0;
            while (sum < 30)
            {
                climb += 3;
                sum = climb;
                climb -= 2;
                day++;
                Console.WriteLine("第{0}天爬了{1}米", day, sum);
            }
            Console.WriteLine(day);
            //一只蝸牛在井底,井深30米,蝸牛每天爬3米,晚上滑2米,請問蝸牛要爬多少天,才能爬出井口
            //位置 snailPos   
            //井深 well  
            //天數 day
            //爬行速度 speed
            //掉落速度 drop
            #region 沒學break之前
            int snailPos = 0;
            int well = 30;
            int day = 0;
            int speed = 3;
            int drop = 2;
            while (snailPos < well)
            {
                //晚上滑
                if (day != 0)
                {
                    snailPos -= drop;
                }
                //每天爬
                snailPos += speed;
                //過了一天
                day++;
                Console.WriteLine("第{0}天爬了{1}米", day, snailPos);
            }
            Console.WriteLine(day);
            #endregion
            #region break方法
            int snailPos = 0;
            int well = 30;
            int day = 1;
            int speed = 3;
            int drop = 2;
            while (true)
            {
                //蝸牛爬
                snailPos += speed;
                Console.WriteLine("第{0}天爬了{1}米", day, snailPos);
                //爬完后立馬問,到井口沒
                if (snailPos >= well)
                {
                    break;
                }
                //晚上滑
                snailPos -= drop;
                //過了一天
                day++;
            }
            Console.WriteLine(day);
            #endregion
            //向控制台輸出1到100之間所有整數的和,如果和加到了500,就終止循環,並且打出這個數
            int count = 1;
            int sum = 0;
            while (count <= 100)
            {
                sum += count;
                Console.WriteLine(sum);
                if (sum > 500)
                {
                    Console.WriteLine("那個數是{0}", sum); break;
                }
                count++;//變換量 盡可能是放在處理過程之后
            }
            //找出100內所有素數。素數/質數:只能被1和這個數字本身整除的數字,1不是質數, 最小的質數是2。
            #endregion
            #region continue方法
            //如果在使用continue調整整個循環的步驟,不建議使用continue。
            //編程 = 算法(步驟) + 數據結構
            //用while、continue實現計算1到100(包含)之間的除了能被7整除之外,所有的整數
            //方法一:補丁版(編程思路不建議使用)
            //1、num++(變化過程)是絕對不能在continue的后面
            //補丁:把num++放在continue前面,由於循環體可以看首尾相連的塊,所以我們可以把某段代碼放到前面,但算法不能改
            //2、結果不正確,起始值不正確:大1,結束值不正確:大1
            //補丁:起始值減1
            //補丁:結束值(邊界值)把等於號拿掉
            int num = 1;
            int sum = 0;
            num--;
            while (num < 100)
            {
                num++;
                if (num % 7 == 0)
                {
                    continue;
                }
                sum += num;
                Console.WriteLine(num);
            }
            Console.WriteLine(sum);
            //方法二
            int num = 1;
            int sum = 0;
            num--;
            while (num <= 100)
            {
                if (!(num % 7 == 0))
                {
                    sum += num;
                    Console.WriteLine(num);
                }
                num++;
            }
            Console.WriteLine(sum);
            #endregion
            #region do while語句
            //常用於用戶名和密碼輸入
            //打豆豆,當豆豆血量高於50的時候,他會說沒吐,小於50時,他會說:別打了,吐了
            //用do while循環打到豆豆吐為止
            int health = 100;
            do
            {
                Console.WriteLine("你暴打了一頓豆豆,然后問他:吐嗎?");
                health -= 10;//條件變換
                if (health > 50)
                {
                    Console.WriteLine("豆豆說:不吐");
                }
                else
                {
                    Console.WriteLine("豆豆說:別打了,吐了,吐了");
                }
                Console.ReadKey(true);
            } while (health > 50);//while后要加分號
            #endregion
            #region do while練習
            //豆豆演出
            bool ok = false;
            do
            {
                Console.WriteLine("豆豆把歌曲唱了一遍");
                Console.WriteLine("老師是否滿意:(y/n)");
                while (true)
                {
                    string i = Console.ReadLine();
                    if (i == "y")
                    {
                        Console.WriteLine("老師滿意了,豆豆可以回去了"); ok = true; break;
                    }
                    else if (i == "n")
                    {
                        Console.WriteLine("老師不滿意,豆豆再練習一遍"); break;
                    }
                    else
                    {
                        Console.WriteLine("輸入有誤,請重新輸入");
                    }
                }
                if (ok) { break; }
            } while (true);
            //用戶名和密碼
            do
            {
                Console.WriteLine("請輸入用戶名");
                string user = Console.ReadLine();
                Console.WriteLine("請輸入密碼");
                string password = Console.ReadLine();
                if (user == "admin" && password == "888888")
                {
                    Console.WriteLine("密碼正確"); break;
                }
                else
                {
                    Console.WriteLine("輸入有誤,請重新輸入");
                }
            } while (true);
            //輸入姓名
            do
            {
                Console.WriteLine("請輸入你的姓名");
                Console.WriteLine("輸入q結束");
                string inPut = Console.ReadLine();
                if (inPut == "q")
                {
                    Console.WriteLine("輸入正確,程序結束"); break;
                }
            } while (true);
            #endregion
        }
    }
}

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace m1w2d1_exercise
{
    class Program
    {
        static void Main(string[] args)
        {
            #region 循環小練習
            //一、向控制台輸出1到100之間所有整數的和
            int count = 1;
            int sum = 0;
            while (count <= 100)
            {
                sum += count;
                count++;//變換量 盡可能是放在處理過程之后
            }
            Console.WriteLine(sum);
            //二、求1 - 100之間所有偶數的和?
            int count = 1;
            int sum = 0;
            for (int i = 1; i <= 100; i++)
            {
                if (count % 2 == 0)
                {
                    sum += count;
                }
                count++;
            }
            Console.WriteLine(sum);
            //三、求100 - 999之間的水仙花數,例如:153 = 1 * 1 * 1 + 5 * 5 * 5 + 3 * 3 * 3
            //取某一位等於這個數 余這個位的上一位,如取百位,余千,然后與本位相除,如百位,除一百
            //abc = a * a * a + b * b * b + c * c * c;
            for (int i = 100; i <= 999; i++)
            {
                int a = (i % 1000) / 100;
                int b = (i % 100) / 10;
                int c = (i % 10) / 1;
                if (i == a * a * a + b * b * b + c * c * c)
                {
                    Console.WriteLine(i);
                }
            }
            //四、明天豆豆就要登台演出了,老師說再把明天演出的歌曲唱一遍。如果老師滿意,
            //豆豆就可以回去了,否則就需要再練習一遍,直到老師滿意為止。(y / n)
            bool ok = false;
            do
            {
                Console.WriteLine("豆豆把歌曲唱了一遍");
                Console.WriteLine("老師是否滿意:(y/n)");
                while (true)
                {
                    string i = Console.ReadLine();
                    if (i == "y")
                    {
                        Console.WriteLine("老師滿意了,豆豆可以回去了"); ok = true; break;
                    }
                    else if (i == "n")
                    {
                        Console.WriteLine("老師不滿意,豆豆再練習一遍"); break;
                    }
                    else
                    {
                        Console.WriteLine("輸入有誤,請重新輸入");
                    }
                }
                if (ok) { break; }
            } while (true);
            //五、要求用戶輸入用戶名和密碼,只要不是admin、888888就一直提示用戶名或密
            //碼,請重新輸入。
            do
            {
                Console.WriteLine("請輸入用戶名");
                string user = Console.ReadLine();
                Console.WriteLine("請輸入密碼");
                string password = Console.ReadLine();
                if (user == "admin" && password == "888888")
                {
                    Console.WriteLine("密碼正確"); break;
                }
                else
                {
                    Console.WriteLine("輸入有誤,請重新輸入");
                }
            } while (true);
            //六、不斷提示請輸入你的姓名,輸入q結束。
            do
            {
                Console.WriteLine("請輸入你的姓名");
                Console.WriteLine("輸入q結束");
                string inPut = Console.ReadLine();
                if (inPut == "q")
                {
                    Console.WriteLine("輸入正確,程序結束"); break;
                }
            } while (true);
            //七、求數列  1,1,2,3,5,8,13, ... 的第20位數字是多少?
            int count1 = 1;
            Console.WriteLine(count1);
            int count2 = 1;
            Console.WriteLine(count2);
            int count3 = count1 + count2;
            for (int i = 3; i <= 20; i++)
            {
                count1 = count2;
                count2 = count3;
                count3 = count1 + count2;
                Console.WriteLine(count3);
            }
            //八、假如火星2016年培養學員10萬人,每年增長80 %,請問按此速度增長,
            //到哪一年培訓的學員人數將達到100萬人?
            int year = 2016;
            float stu = 10f;
            float rate = 0.8f;
            while (true)
            {
                year++;
                stu += stu * rate;
                if (stu >= 100f)
                {
                    Console.WriteLine("{0}年培訓的學員人數將達到100萬人", year); break;
                }
            }
            //九、輸入班級人數,然后依次輸入學員成績(需提示當前是第幾個學員),計算班
            //級學員的平均成績和總成績。
            Console.WriteLine("輸入班級人數");
            int num = int.Parse(Console.ReadLine());
            float score = 0;
            float sum = 0;
            float aver = 0;
            bool isInputOk = false;
            for (int i = 1; i < num; i++)
            {
                Console.WriteLine("請輸入第{0}位同學的成績", i);
                score = float.Parse(Console.ReadLine());
                sum += score;
                //Console.WriteLine("是否繼續輸入(y/n)");
                //while (true)
                //{
                //    string j = Console.ReadLine();
                //    if (j == "y")
                //    {
                //        break;
                //    }
                //    else if (j == "n")
                //    {
                //        isInputOk = true; break;
                //    }
                //    else
                //    {
                //        Console.WriteLine("輸入有誤,請重新輸入");
                //    }
                //}
                //if (isInputOk)
                //{
                //    break;
                //}
            }
            aver = sum / num;
            Console.WriteLine("班級學員的平均成績為{0},總成績為{1}", aver, sum);
            //十、老師問學生,這道題你會作了嗎?如果學生答“會了(y)”,則可以放學,
            //如果學生不會做(n),則老師再講一遍,再問學生是否會做了。。。
            //直到學生會了為止,才可以放學
            //直到學生會了或老師給他講了10遍還不會,都要放學
            bool ok = false;
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("老師問:這道題你會作了嗎?");
                Console.WriteLine("學生答:會了/不會做(y/n)");
                while (true)
                {
                    string ansanswer = Console.ReadLine();
                    if (ansanswer == "y")
                    {
                        Console.WriteLine("你真聰明"); ok = true; break;
                    }
                    else if (ansanswer == "n")
                    {
                        Console.WriteLine("老師又講了一遍"); break;
                    }
                    else
                    {
                        Console.WriteLine("輸入有誤,請重新輸入");
                    }
                }
                if (ok)
                {
                    break;
                }
            }
            Console.WriteLine("放學了");
            //十一、找出100內所有素數。素數 / 質數:只能被1和這個數字本身整除的數字,1不是質數, 最小的質數是2。
            //如果你遇到一個復雜,要抽象其子問題
            //子問題:某一個數是不是質數
            for (int j = 2; j <= 100; j++)
            {
                int num = j;
                for (int i = 2; i <= num; i++)
                {
                    if (i == num)
                    {
                        Console.WriteLine("{0}是一個質數", i);
                        break;
                    }
                    if (num % i == 0)
                    {
                        //Console.WriteLine("{0}不是一個質數", i);
                        break;
                    }
                }
            }
            #endregion
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM