目录

一、选择结构

1.基础 if 语句

2.if...else 双分支判断

3.if...else if...else 多分支判断

4.if...if多条件

5.if...else 嵌套

6.switch...case

7.练习

二、关键字

1.break关键字

2.continue关键字

3.练习

三、循环结构

1.while循环

2.do...while循环

3.for循环


一、选择结构

1.基础 if 语句

// ()需要写一个条件,例如 大于 小于 等于 不等 是否为null等条件
//{} 代码块

if (true) // true条件成立了
{
    Console.WriteLine("看看代码是否执行");
}

if (false)// false 不成立
{
    Console.WriteLine("代码不执行"); // 检测无法执行的代码
}

// 用户输入一个年龄 判断年龄是否超过18岁,如果超过打印成年了
int age = int.Parse(Console.ReadLine());
if (age > 18)
{
    Console.WriteLine("成年了 想咋耍就咋耍");
}

2.if...else 双分支判断

// 2只有俩种情况的流程控制
// if(){}...else{}

int score = 60;
//if 如果条件成立 执行{}
if (score>=90)
{
    Console.WriteLine("A");
}
else //其余的 和if条件的相反score<90
{
    Console.WriteLine("A-");
}

3.if...else if...else 多分支判断

//3 多条件流程控制
// if(){}...else if(){}....else{}

int age1 = 12;
if (age1>=0 && age1<=14) // age1在0-14之间
{
    Console.WriteLine("总角");
}
else if (age1>14 && age1<=24)
{
    Console.WriteLine("弱冠-豆蔻");
}
else if (age1>24 && age1<=40)
{
    Console.WriteLine("三十而立");
}
else if (age1>40 && age1<=70)
{
    Console.WriteLine("知命之年");
}
else
{
    Console.WriteLine("耄耋");
}

4.if...if多条件

//4 多条件流程控制
// if...if... 每个if都需要进行判断

int count = 90;
if (count>=90)
{
    Console.WriteLine("count大于等于90");
    count = 60;
}
if (count<70)
{
    Console.WriteLine("count小于70");
}

5.if...else 嵌套

//5 条件嵌套
//先判断是不是男生,再判断是年龄是否超过18,
// 如果不是男生 对应的提示
int age2 = 10;
string sex = "女";
if (sex=="男") // 满足是男生
{
    if (age2>=18)
    {
        Console.WriteLine("是男生并且年龄超过18,可以结婚");
    }
    else //是男生 但是年龄不超过18
    {
        Console.WriteLine("不到18不允许结婚");
    }
}
else //不是男生
{
    Console.WriteLine("不是男生");
}

6.switch...case

 //switch 也是属于条件流程控制,可以替换if流程控制  
 //switch 选择
 //() 具体的变量 根据哪个变量进行判断
 //每个case 是变量一种可取情况
 //每个case后面需要添加break进行跳出

    int day = 8;    // 根据day进行显示不同周几
    switch (day)
    {
        case 1: //day==1
            Console.WriteLine("星期一");
            break;
        case 2: // day==2
            Console.WriteLine("星期二");
            break;
        case 3:
            Console.WriteLine("星期三");
            break;
        case 4:
            Console.WriteLine("星期四");
            break;
        case 5:
            Console.WriteLine("星期五");
            break;
        case 6:
            Console.WriteLine("星期六");
            break;
        case 7:
            Console.WriteLine("星期天");
            break;
        default: // day!=1 2 3 4 5 6 7
            Console.WriteLine("输入星期有误");
            break;
    }
int count = 4;
    switch (count)
    {
        // 如果有俩个case执行的代码一样,可以把case写在一起 前面case就不要写break
        case 1:
        case 2:
            Console.WriteLine("count==2");
            break; // 跳出流程控制 注意break后面不要写代码
            //Console.WriteLine("");
        case 3: // count ==3
            Console.WriteLine("count==3");
            break;
        default:
            break;
    }
 // switch() 可以跟字符串类型
    string name = "小张三";
    switch (name) // name有哪几种情况
    {
        case "大山": //如果name == 大山 、 小张 张三 执行逻辑一样
        case "小张":
        case "张三":
            Console.WriteLine("叫对了");
            break;
        default:
            Console.WriteLine("叫错了");
            break;
    }
 //定义Season的枚举类型
    Season 季节 = Season.Summer; // 季节就是变量 值是Season.Summer
    switch (季节) // 可以是一个枚举类型
    {
        case Season.Spring:
            Console.WriteLine("春天");
            break;
        case Season.Summer: // 季节==Season.Summer
            Console.WriteLine("夏天");
            break;
        case Season.Autumn:
            Console.WriteLine("秋天");
            break;
        case Season.Winter:
            Console.WriteLine("冬天");
            break;
        default:
            break;
    }


// 枚举类型:值类型
enum Season
{
    Spring, //春天
    Summer, //夏天
    Autumn, //秋天
    Winter  //冬天
}

7.练习

1.判断数字是不是偶数

//#region 和 #endregion 表示一块区域
#region 1 判断数字是不是偶数
int num = 9;
if (num % 2 == 0) // 余数为0 证明是偶数
{
    Console.WriteLine("是偶数");
}
else
{
    Console.WriteLine("是奇数");
}
#endregion

2.判断年是不是闰年

#region 2 判断年是不是闰年
int year1 = 1900;
//(year1%4==0 && year1%100!=0) 满足次条件
// year1%400==0 满足这个条件
// 满足其一就是闰年
if ((year1 % 4 == 0 && year1 % 100 != 0) || year1 % 400 == 0)
{
    // $,进行拼接,只需要写一个字符串,中间有需要显示变量的,把变量使用{}即可
    Console.WriteLine($"{year1}年是闰年");
}
else
{
    Console.WriteLine($"{year1}年是平年");
}
#endregion

3.要求用户输入车辆类型(轿车、卡车、摩托车)和停车时长(小时),根据车辆类型和停车时长计算停车费,用:轿车每小时5元;卡车每小时10元;摩托车每小时3元;停车不足1小时按1小时计费。

#region 3
//要求用户输入车辆类型(轿车、卡车、摩托车)和停车时长(小时),根据车辆类型和停车时长
//计算停车费用:轿车每小时5元;卡车每小时10元;摩托车每小时3元;停车不足1小时按1小时计费。

Console.WriteLine("请输入车辆的类型");
string type = Console.ReadLine(); //类型

Console.WriteLine("请输入停车时长");
double hour = double.Parse(Console.ReadLine()); //时长

double sum = 0; // 总价格

if (hour < 1) // 小时小于1
{
    hour = 1; //hour 安按照1小时计算
}

/*
if (type == "轿车")
{
    sum = 5 * hour;
}
else if (type == "卡车")
{
    sum = 10 * hour;
}
else
{
    sum = 3 * hour;
}
*/

//把上面注释改成三目运算
//判断type == "轿车" 如果等于了 sum = 单价 * 5
//type == "卡车" ? 10 * hour 满足是卡车的时候
//sum = hour; 不满足卡车 和轿车时候
sum = type == "轿车" ? 5 * hour :
      type == "卡车" ? 10 * hour : 3 * hour;

Console.WriteLine("总费用为:" + sum);
#endregion

4.输入年份、月份,输出该月份有多少天?

//12月
    //1 3 5 7 8 10 12 都是31天
    //4 6  9 11  都是30天
    //2 闰年29天 平年28天

    int day1 = 0;
    int year = int.Parse(Console.ReadLine()); // 输入年份
    int month = int.Parse(Console.ReadLine()); // 输入月份
    switch (month)
    {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
            day1 = 31;
            break;
        case 4:
        case 6:
        case 9:
        case 11:
            day1 = 30;
            break;
        case 2:
            if((year%4==0&&year%100!=0)|| year%400==0){
                day1=29
             }else{
                day1=28
             }
               break;
        default:
            break;
    }
    Console.WriteLine($"当前是{month}月,本月有{day1}天");
}

二、关键字

1.break关键字

        break 是一种控制流语句,用于立即终止 循环 switch 语句,无需等到循环条件变为 false , 在 while 循环中, break 常用于满足特定条件时直接退出循环,而不继续剩余的循环逻辑。
        语法格式如下,在该例子中,只要内部的条件达成,导致 break 语句被执行,就会立即终止循环,就算表达式执行结果 为 true ,也会 立即终止 循环。
while(表达式){
    // 循环体
    if(某个条件达成){
        break;
    }
}

2.continue关键字

        在循环中, continue 是一种控制语句,用于跳过当前迭代的剩余代码,直接进入下一次循环。

        与 break 不同的是, continue 不会终止整个循环,而是跳过当前迭代后继续执行循环的下一个迭代。

while(条件){
  Conwole.WriteLine("A");
  if(跳过条件){
       continue;
  }
  Conwole.WriteLine("B");
}

3.练习

// break 跳出整个循环
int i1 = 0;
while (i1 < 4)
{
    i1++;
    if (i1 == 2)
    {
        break;
    }
    Console.WriteLine(i1);   //1
}
//continue: 继续,不会跳出循环,只会跳出当前循环,后续的循环继续执行
int i = 0;
while (i < 4)
{
    i++;
    if (i == 2)
    {
        continue;//继续下次循环
    }
    Console.WriteLine(i);  //1 3 4
}

三、循环结构

1.while循环

循环:当代码需要执行很多次的时候 ,可以使用循环语句

while循环 

while(){}:当小括号条件成立了,执行{}里面的东西,条件不成立的时候,循环就结束了

while (true) //true 就是永远成立 一直执行{}
{
    Console.WriteLine("死循环");
    break;//跳出死循环 只会执行一次
}

while (true) //死循环
{
    Console.WriteLine("请输入yes/no"); //如果输入的是yes 一直输入,输入为no的时候 跳出循环
    string name = Console.ReadLine(); //等待用户输入的一个过程
    if (name == "no")
    {
        break;
    }
}

// 使用while循环 执行有限次数循环
int i = 0;
while (i < 10)
{
    Console.WriteLine(i);
    //更新i的值 直到i的值大于等于10,条件不成了,循环就不在执行
    i++;
}

/* 1 先执行 i = 0
 * 2 再判断i是否小于10 如果小于10执行{}
 * 3 再去i++ 变成1
 * 4 再去判断i是否小于10 如果小于10 再去执行{}
 * 5 在执行i++
 *
 */

练习:

   (1)求0+1+2....+100的和。

int j = 0;
int sum = 0;//总和
while (j < 101)
{
    sum = sum + j; // j 0 1 2 3 ...100
    j++;
}
Console.WriteLine(sum);  //5050

(2)求0-100之间偶数和。

int a = 0;
int sum1 = 0;
while (a < 101)
{
    if (a % 2 == 0)
    {
        sum1 += a;
    }

    // a+=2; a 0 2 4 6 8...100
    a++; // a  0 1 2 3 ...
}
Console.WriteLine(sum1);//2550
//输出1-100之间所有的偶数 continue

int b = 0; //1初始值
int sum = 0;
while (b < 101) //2循环条件
{
    b++;   //循环递增量
    if (b % 2 != 0)   // b是奇数,需要跳出来
    {
        continue;
    }
    sum += b;
}
Console.WriteLine(sum);  //2550

(3)求0-100之间能够被三整除的偶数,找到第一个。

int count = 1;
while (count < 101)
{
    if (count % 3 == 0 && count % 2 == 0)
    {
         Console.WriteLine(count);
         break;                       //找到满足的第一个数,跳出循环
    }
    count++;
}

(4)输入一个数,实现阶乘

 Console.WriteLine("请输入一个数:");
 int num2 = Convert.ToInt32(Console.ReadLine());

 int i = 1;
 int sum2 = 1;
 string s = "";

 while (i <= num2)
 {
     sum2 *= i;
     // 三元运算符简化判断:i是1时,就不写*,否则写*
     s += i == 1 ? $"{i}": $"*{i}";
     i++;
 }

 Console.WriteLine($"{s}={sum2}");

2.do...while循环

        do-while 也是C#中的一种循环结构,他的特点是 先执行一次代码块,然后再检查条件 。无论条件是否为 true ,代码块都至少会被执行一次。
        do-while 循环适合用于 必须执行一次逻辑后,再根据条件决定是否继续循环 的场景
do{
    // 循环体代码
  }while(条件);

练习:

(1)如果用户输入一个小于0的数 一直输入。

int num1;
do
{
    Console.WriteLine("请输入一个正数");
    num1 = int.Parse(Console.ReadLine());
} while (num1 < 0); //num1 小于0的时候 执行{}

(2)输入一个数,实现阶乘

int i1 = 1; // 初始值
int sum3 = 1; //乘积
Console.WriteLine("请输入一个数");
int num3 = int.Parse(Console.ReadLine()); // 用户输入

do
{
    sum3 *= i1;
    i1++;
} while (i1 <= num3); // 条件

Console.WriteLine(sum3);

3.for循环

1.单层for循环
语法:
int i =0; 代表循环开始的初始值从0开始
i<10;代表循环的条件,i<10时重复执行代码块
i++ 代表 i每次循环结束之后的递增量
注意 每个符号都是英文状态下的符号,初始条件和循环条件后都要加分号
for(int i = 0; i<10;i++ )
{
   //循环语句执行
}
执行顺序:
①先执行初始条件 int i = 0; (初始条件只执行一次)
②再执行判断条件 i < 10; 成立:执行③ 不成立:执行⑤
③执行 { 循环语句 }
④执行迭代变量 i++ ,然后执行②
⑤退出 for 循环
// 第一种:通过修改初始值进行控制
for(int i = 1;i<5;i++)
{
  Console.WriteLine("i="+i); //循环次数为1 2 3 4
}

// 第二种:通过修改循环条件进行控制
for(int i = 0;i<5;i++)
{
  Console.WriteLine("i="+i);  //循环次数为 0 1 2 3 4
}

第三种:通过循环递增量进行控制
for(int i = 0;i<5;i+=2)
{
  Console.WriteLine("i="+i);  //循环次数为 0 2 4
}

// 第四种:利用for循环进行倒序
for (int i = 5; i >=0; i--)
{
  Console.WriteLine("i=" + i);  //i的值为5 4 3 2 1 0
}

练习:

(1)输入一个数,实现阶乘。

Console.WriteLine("请输入一个数:");
int num2 = Convert.ToInt32(Console.ReadLine());

int sum2 = 1;
for (int i = 1; i <= num2; i++)
{
    sum2 *= i;
}

//  Enumerable 是 C# 准备的「快速生成连续数字」的工具类。
// 最常用的只有一个:Enumerable.Range(1,5) =>从 1 开始,生成 5 个数字=>1 2 3 4 5
string s = string.Join("*", Enumerable.Range(1, num2));
Console.WriteLine($"{s}={sum2}");

(2)目标是搬砖500个,第一次搬砖1个,后面因为更加熟练,每次递增一倍,1、2、4、8、     16、  32、64、128、256...,搬砖500个需要多少次?

//for 循环
   int total =0;  // 搬砖数量
   int count = 0; // 搬砖次数
  
   for (int i = 0; total<=500; i++) {
       count++;
       total += (int)Math.Pow(2,i);                                              
   }
   Console.WriteLine(count);      //9 
//while 循环
   int totalBrick = 0;  // 搬砖数量
   int countBrick = 0; // 搬砖次数
   int brick = 1;  // 本次要搬的数量,第一次是1,之后每次翻倍

   while (totalBrick <= 500) {
       countBrick++;
       totalBrick += brick;
       brick *= 2;
   }
   Console.WriteLine(countBrick); //9

(3)有一个学校,现在有8个人,每年学院增长23%,几年后学员可以达到100人?

  //for 循环
  double num1 = 8;  //人数
  double year1 = 0; // 年数

  for ( int i=0;num1<=100;i++) {
      year1++;
      num1 = num1 * 1.23;
  }
  Console.WriteLine(year1);  //13
 // while循环
    int year = 0;  //   年数
    double num = 8;    //学校人数

    while (num <= 100) {
        year++;
        num *= 1.23;           
    }
    Console.WriteLine(year);  //13

(4)判断用户输入的数字是否为素数,素数是指只能被 1 和它本身整除的数字。

//for 循环
   int a1 = 13;
   bool isSuShu = true;

   for (int i=2;i<a1;i++) {
       if (a1 % 2 == 0) {
           isSuShu = false;
           break;
       }
   }
   if (!isSuShu) { Console.WriteLine("不是素数"); }
   else { Console.WriteLine("是素数"); }
//while 循环
    int a = 13;       // 要判断的数字
    int b = 2;        // 从 2 开始除(因为素数不能被 2~a-1 整除)
    bool isSu = true; // 先假设它是素数

    // 循环:b 从 2 一直增加到 a-1
    while (b < a)
    {
        // 如果 a 能被 b 整除 → 说明不是素数
        if (a % b == 0)
        {
            isSu = false;
            break; // 找到因子,直接退出循环
        }
        b++;       // 没找到,继续试下一个数
    }

    // 输出结果
    if (!isSu)
        Console.WriteLine("不是素数");
    else
        Console.WriteLine("是素数");
2.嵌套for循环

规则:外层走 1 次,内层完整跑完一整轮

// 外层循环
for (int i = 起始值; 条件; 自增)
{
    // 内层循环
    for (int j = 起始值; 条件; 自增)
    {
        执行代码;
    }
}

练习:

(1)打印矩形星号

// 5行5列 *
for (int i = 1; i <= 5; i++)
{
    for (int j = 1; j <= 5; j++)
    {
        Console.Write("* ");
    }
    Console.WriteLine(); // 换行
}

(2) 九九乘法表(经典必写)

for (int i = 1; i <= 9; i++)
{
    for (int j = 1; j <= i; j++)
    {
        Console.Write($"{j}*{i}={i*j}\t");
    }
    Console.WriteLine();
}

四、Math、goto、可空类型

Math:提供一些关于数学方面的函数, 使用Math函数 一般都是通过Math.函数名, 原因是函数static静态函数, 静态函数使用的时候通过类名.函数进行使用。

//1 abs() 求绝对值
Console.WriteLine(Math.Abs(-10));

//2 Floor() 向下求整
Console.WriteLine(Math.Floor(2.3)); //2
Console.WriteLine(Math.Floor(2.7)); //2

//3 Ceiling(2.3) 向上求整
Console.WriteLine(Math.Ceiling(2.3));//3
Console.WriteLine(Math.Ceiling(2.9));//3

//4 Round() 四舍六入五取偶数
Console.WriteLine(Math.Round(3.5));//4
Console.WriteLine(Math.Round(2.5));//2, .5是中间值, 在进行舍入的时候, 取离他最近的偶数

Console.WriteLine(Math.Round(1.235, 2));// 第二个参数2的意思保留俩位小数 1.24
Console.WriteLine(Math.Round(1.225, 2));//1.23

// 要想使用正常四舍五入
//参数1 :2.5 指定舍入的数据
//参数2 舍入的规则, 如果MidpointRounding.AwayFromZero 正常的四舍五入
//如果MidpointRounding.ToEven 取最近的偶数
Console.WriteLine(Math.Round(2.5, MidpointRounding.AwayFromZero));//3
Console.WriteLine(Math.Round(1.225, 2, MidpointRounding.AwayFromZero));//1.23

goto语句不建议使用

goto语句:在需要重复执行的代码前面添加一个标记,在后面需要重复执行了 只需要使用goto 加上标记即可

inputSex: goto 语句的标签名。也是需要遵循小驼峰命名法则,定义标签时候,定义在代码的前一行

inputSex:
    Console.WriteLine("请输入一个性别");
    string str = Console.ReadLine();
    if (str=="男")
    {
        Console.WriteLine("性别是男");
    }
    else if (str=="女")
    {
        Console.WriteLine("性别是女");
    }
    else
    {
        Console.WriteLine("输入性别不合法 请重新输入");
        goto inputSex;// 去重复执行inputSex
    }

C# 里值类型(int、double、bool、DateTime 等)默认不能存 null,但实际开发中经常需要表示「无值、空、未设置」的状态。

 C# 提供了 可空类型: 数据类型? = 可以存 null + 正常数值

// 普通值类型(不能存null)
int normalInt = 10;

// 可空类型(能存null,也能存正常数字)
int? nullableInt = null;
   string s = "";//空字符串
    // 值类型只能表示数字, 不能表示null
    // 引用类型可以表示null
    string s1 = null;
    //int b = null;
    int a = 10; //只能正数和负数以及0,但是不能表示null

    //如果想让值类型 除了能表示正常的范围数据还能表示null 可以使用数据类型?变量=null;
    // 扩大类型表示范围

    int? c = null;//在变量前添加一个? 就可以表null
    c = 19; //可以给自己赋值为其他的

    //int d = c;//等号左右俩边范围不匹配, c可以取null,但是d不能取null。

    //可以使用双??进行赋值给整型变量,
    //把包包含null类型转成不包含的null类型的数据
    int d = c??10; // 如果c为null  取后面数字, 如果c不为null 取c的值
    Console.WriteLine(d);

更多推荐