当前位置: 首页 > news >正文

C#基础语法(2)

### 练习
一、变量和数据类型
- 1. 变量定义与赋值
```cs
using System;
namespace Name
{
    class Program
    {
        public static void Main(string[] args)
        {
            int age = 20;
            double height = 1.75;
            string name = "张三";
            bool isStudent = true;
            Console.WriteLine($"年龄: {age}, 姓名: {name}, 身高: {height}, 是否学生: {isStudent}");
        }
    }
}
```
- 2. 数据类型转换
```cs
 string numStr = "123";
            //将numStr转换为整数类型
            int num = int.Parse(numStr);
            int res = num + 456;
            Console.WriteLine(res.ToString());
```

二、运算符
1. 算术运算符
```cs
int a = 10;
int b = 3;
Console.WriteLine($"a+b={a+b},a-b={a-b},a*b={a*b},a/b={a/b},a%b={a%b}");
```

2. 比较和逻辑运算符
```cs
            int x = 20;
            int y = 30;
            bool res = x == y;
            bool res1 = x != y;
            bool res2 = x > y;
            bool res3 = x < y;
            bool res4 = x >= y;
            bool res5 = x <= y; 
            Console.WriteLine($"{res},{res1},{res2},{res3},{res4},{res5}");
``` 

3. 
```cs
    bool res = x > 10 && y < 40;
```

三、流程控制
1. 条件语句
```cs
        Console.WriteLine("请输入分数(0-100)");
        string input = Console.ReadLine();
        int score;
        //int.TryParse(input, out int score):int.TryParse 是一个尝试将字符串转换为整数的方法。它有两个参数:第一个是要转换的字符串 input,第二个是输出参数 out int score,用于存储转换后的整数值。
        if (!string.IsNullOrEmpty(input) && int.TryParse(input, out score) && score >= 0 && score <= 100)
        //  空的 string.IsNullOrEmpty() 调用:!string.IsNullOrEmpty() 应该包含一个参数,即 input。
        //  未赋值的局部变量 score:int.TryParse 应该使用 out score 而不是 out int score,因为 score 已经在前面声明过了。
        {
            int GradeLevel = score / 10;
            string Grade;
            switch (GradeLevel)
            {
                case 10:
                case 9:
                    Grade = "A";
                    break;
                case 8:
                    Grade = "B";
                    break;
                case 7:
                    Grade = "C";
                    break;
                case 6:
                    Grade = "D";
                    break;
                default:
                    Grade = "E";
                    break;                                        
            }
            Console.WriteLine($"成绩等级:{Grade}");
        }
        else
        {
            Console.WriteLine("输入字符无效");
        }
```

2. 循环语句
```cs
            for (int i = 1; i < 11; i++)
            {
               int res = i*i;
               Console.WriteLine(res);
            }
```

3. 累加和
```cs
            int i = 1;
            int sum = 0;
            while (i<=100)
            {
                sum += i;
                i++;
            }
             Console.WriteLine(sum);
```

四、方法
1. 方法定义与调用
```cs
    public class Program
    {
        public int Add(int n,int y)
        {
            int res = n + y;
            return res;
        }
        public static void Main(string[] args)
        {
            //   创建 Program 类的实例
            Program pro = new Program();
            // 通过实例调用非静态方法 Add
            int result = pro.Add(6, 1);
             Console.WriteLine(result);
        }
    }
```

2. 方法重载
```cs
    public class Calculator
    {
        // 重载方法:参数顺序为 int 和 double
        public double Multiply(int a, double b)
        {
            return a * b;
        }
        // 重载方法:参数顺序为 double 和 int
        public double Multiply(double a, int b)
        {
            return a * b;
        }
        public static void Main(string[] args)
        {
            // 根据命名class类
            Calculator calculator = new Calculator();

            double result1 = calculator.Multiply(5, 3.5);
            double result2 = calculator.Multiply(5.5, 3);

            Console.WriteLine("int 和 double 相乘结果: " + result1);
            Console.WriteLine("double 和 int 相乘结果: " + result2);
        }
    }
```

五、字符串操作
1. 字符串拼接
```cs
        string firstName = "张";
        string lastName = "三";
        Console.WriteLine($"{firstName}{lastName}");
```

2. 字符串方法
```cs
        string sentence = "Hello, World!";
        string res1 = sentence.ToUpper();
        string res2 = sentence.Replace("World","C#");
        Console.WriteLine(res1);
        Console.WriteLine(res2);
```

六、综合练习
1. 简单的计算器
```cs
    public static void Main(string[] args)
    {
        Console.WriteLine("请输入第一个数字:");
        double num1 = Convert.ToDouble(Console.ReadLine());
        Console.WriteLine("请输入第二个数字:");
        double num2 = Convert.ToDouble(Console.ReadLine());
        Console.WriteLine("请输入运算符:(+、-、*、/)");
        char op = Console.ReadLine()[0];

        double res = 0;
        switch (op)
        {
            case '+':
                res = num1 + num2;
                break;
            case '-':
                res = num1 - num2;
                break;
            case '*':
                res = num1 * num2;
                break;
            case '/':
                if (num2 != 0)
                {
                    res = num1 / num2;
                }
                else
                {
                    Console.WriteLine("错误: 除数不能为零!");
                    return;
                }
                break;
            default:
                Console.WriteLine("错误: 无效的运算符!");
                return;
        }
         Console.WriteLine("结果: {0} {1} {2} = {3}", num1, op, num2, res);
    }
```

2. 猜数字游戏
```cs
using System;
public class Calculator
{
    public static void Main(string[] args)
    {
        Random ran = new Random();
        int res = ran.Next(1, 3);
        Console.WriteLine("猜猜看,这个数字是多少?");
        while (true)
        {
            Console.WriteLine("请输入一个数字:");
            int userGuess;
            if (int.TryParse(Console.ReadLine(), out userGuess))
            {
                if (userGuess == res)
                {
                    Console.WriteLine("恭喜你,猜对了!程序结束。");
                    break; // 结束循环
                }
                else if (userGuess < res)
                {
                    Console.WriteLine("猜小了,请再试一次!");
                }
                else
                {
                    Console.WriteLine("猜大了,请再试一次!");
                }
            }
            else
            {
                Console.WriteLine("输入无效,请输入一个数字!");
            }
        }
    }
}
```

### 笔记
1. 命名空间和类定义
- 使用 `namespace` 关键字定义命名空间,以组织代码并避免命名冲突。
- 使用 `public class` 关键字定义一个公共类。

2. 主方法
- `static void Main(string[] args)` 是程序的入口点,其中 `args` 是一个字符串数组,用于接收命令行参数。

3. 控制台输出
- `System.Console.WriteLine` 方法用于向控制台输出文本信息。

4. 列表操作
- `List<string>` 是一个泛型列表,用于存储字符串类型的元素。
- `new List<string>()` 创建一个新的字符串列表实例。
- `Add` 方法用于向列表中添加单个元素。
- `AddRange` 方法用于向列表中添加一个字符串数组作为元素集合。

5. 循环遍历
- `foreach` 循环用于遍历列表中的每个元素。
- `var item` 在 `foreach` 循环中隐式类型化为当前元素的类型。

6. 变量声明
- `var` 关键字用于隐式类型化局部变量,编译器会根据赋值自动推断变量类型。

7. 数组创建
- `new string[] { "33", "99" }` 创建一个新的字符串数组,并初始化为包含指定字符串元素。

相关文章:

  • lsinitramfs命令
  • 定时器:中央对齐模式剖析
  • 06-排序
  • Java Lambda 表达式的缺点和替代方案
  • 破局与进阶:ueBIM 在国产 BIM 赛道的差距认知与创新实践
  • 【计算机网络】数据链路层——ARP协议
  • Windows【基础操作2】
  • 【WPF】从普通 ItemsControl 到支持筛选的 ItemsControl:深入掌握 CollectionViewSource 用法
  • 基于深度学习的糖尿病视网膜病变图像分类系统的设计与实现 -完整代码+数据
  • 蓝桥杯国赛训练 day1
  • 软硬解锁通用Switch大气层1.9.0系统+20.0.1固件升级 图文教程 附大气层大气层固件升级整合包下载
  • HashMap 的底层原理
  • 【Vmware】虚拟机安装、镜像安装、Nat网络模式、本地VM8、ssh链接保姆篇(图文教程)
  • 0518蚂蚁暑期实习上机考试题3:小红的字符串构造
  • (17)课36:窗口函数的例题:例三登录时间与连续三天登录,例四球员的进球时刻连续进球。
  • 简单爬虫框架实现
  • Android Kotlin 算法详解:链表相关
  • Dify:启动 Web 服务的详细指南
  • Ubuntu 22.04 安装 Nacos 记录
  • ubuntu 20.04挂载固态硬盘
  • 自己做网站微商/seo网站优化报价
  • 微信网页网站怎么做/网络推广营销软件
  • 上海石化有做网站设计的吗/世界最新新闻
  • 网站在线制作平台/新媒体运营怎么自学
  • 专业做家政网站/怎么建网站平台卖东西
  • iis网站开发教程/seo关键词排名技术