C#基本数据类型

常量与变量

常量名和变量名都必须以字母或者下划线开头,后跟数字或字母的组合。

  1. 常量
    const关键字
const double pi = 3.14 ;
  1. 变量
    var声明的变量称为隐式类型的局部变量,这种类型称为匿名类型。
    当不知道什么类型时使用,但是编译器会根据所赋初值来自动推断其类型,属于强类型。

还可以用匿名类型将一组具有初值的只读属性封装到单个对象中,而无需先定义类,在创建类的实例。

var v = new{ ID = "0001" ,Name = "Coral" };
Console.WriteLine("学号:{0},姓名:{1}",v.ID, v.Name);

也可以用于LINQ和Lambda表达式:

int[] scores = new int[] { 97, 92, 81, 60 };
var q = scores.Where((score) => score > 80);
Console.WriteLine($"成绩大于80的有{q.Count()}个");

简单类型

整型

int 4字节有符号整数(32位)
long 8字节有符号整数(64位)

给变量赋值时,也可采用不同进制:
int x1 = 1234;(十进制)
int x1 = 0x1A;(十六进制)加前缀0x
int x1 = 0b1001;(二进制)加前缀0b

浮点型

double y = 2.7;
double z = 2.7E+23; //科学计数法,2.7×10的23次方
float x = 2.7f; //后缀加f,不加默认为double

字符型

转义字符:

转义符说明
\b退格
\r回车
\n换行
\ttab 空格
枚举类型(enum)

表示一组同一类型的常量

public enum MyColor { Red=1,Green,Blue};

Green=2, Blue = 3。

字符串
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace @string
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建字符串变量
            string s1 = "123ABCD";
            string s2 = "this is a string";

            Console.WriteLine(s1);
            Console.WriteLine(s2);

            //比较字符串(s1在前,s2在后,大于返回1,等于返回0,小于返回-1)
            Console.WriteLine("-比较字符串----------------------------");
            Console.WriteLine(string.Compare(s1, s2));//结果为-1
            

            string s3 = "adca";
            string s4 = "aacd";
            string s5 = "aacd";
            Console.WriteLine(string.Compare(s3, s4));//结果为1

            Console.WriteLine("--返回bool类型-------------------------");
            Console.WriteLine(s3 == s4);//结果为false
            Console.WriteLine(s4.Equals(s5));//结果为True

            //查找
            Console.WriteLine("----字符的查找-------------------------");
            Console.WriteLine(s2.Contains("is"));
            Console.WriteLine(s2.Contains("Is"));//区分大小写
            Console.WriteLine();
            Console.WriteLine(s2.StartsWith("this"));//判断是否为这个字符开头
            Console.WriteLine(s2.EndsWith("ing"));//判断是否为这个字符结尾“string”“ing”“g”都可以

            Console.WriteLine("------显示子串的位置--------------------");
            Console.WriteLine(s2.IndexOf("is"));//显示子串的位置(第一个出现的子串)

            Console.WriteLine();
            char[] c = { 'a', 'b', 'h' };
            Console.WriteLine(s2.IndexOfAny(c));//查找c中列出的字符第一次在字符串中出现的位置

            //提取字符
            Console.WriteLine("----------提取字符---------------------");
            string s6 = "abcde";
            Console.WriteLine(s6.Substring(2));//提取2后面所有字符
            Console.WriteLine(s6.Substring(2, 2));//提取2后面2个字符

            //插入、删除、替换
            Console.WriteLine("------------插入、删除、替换-------------");
            Console.WriteLine(s1.Insert(3, "456"));//在第三个位置上添加“456”
            Console.WriteLine(s1.Remove(5));//删除5及其后面全部字符
            Console.WriteLine(s1.Remove(2, 2));//删除2及其后面两个字符
            Console.WriteLine(s1.Replace("123", "0805"));//将某些字符替换成某些字符



            //移除首尾字符(默认为空格)
            Console.WriteLine("-------------------移除首尾字符---------");
            string s7 = "  1998 05.28 ";
            Console.WriteLine(s7.TrimStart());//移除首字符
            Console.WriteLine(s7.TrimEnd());//尾
            Console.WriteLine(s7.Trim());//移除所有空格

            Console.WriteLine(s7.Trim('8'));//???

            //大小写转换
            Console.WriteLine("---------------这是分割线--------------");
            Console.WriteLine(s2.ToUpper());
            Console.WriteLine(s2.ToLower());

            Console.ReadLine();

        }
    }
}

在这里插入图片描述

数组
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace array
{
    class Program
    {
        static void Main(string[] args)
        {
             //数组的应用
            //创建数组
            //一维数组
            Console.WriteLine("---------------一维数组--------------");
            int[] a = new int[5] { 1, 2, 3, 4, 5 };
            Console.WriteLine(a[0]);//显示单个元素

            //全部显示
            for (int i = 0; i < a.Length; i++)
            {
                Console.Write("a[{0}]={1} ", i, a[i]);
            }
            Console.WriteLine();
            //二维数组
            Console.WriteLine("---------------二维数组--------------");
            int[,] b = new int[2, 3] { { 1, 2, 3 }, { 4, 5, 6 } };
            Console.WriteLine(b[1, 1]);
            //显示全部
            for (int i = 0; i < b.GetLength(0); i++)
            {
                for (int j = 0; j < b.GetLength(1); j++)
                {
                    Console.Write("b[{0},{1}]={2} ", i, j, b[i, j]);
                }

            }
            Console.WriteLine();

            //交错数组
            Console.WriteLine("---------------交错数组--------------");
            int[][] c = new int[][]
            {
                new int[]{1,2},
                new int[]{3,4,5}
            };
            Console.WriteLine(c[1][1]);//读取交错数组

            //数组字符串转换
            Console.WriteLine("--------------数组字符串转换-------------");
            string[] str1 = { "123", "ABC", "甲乙丙" };
            string s1 = string.Join(",", str1);
            Console.WriteLine(s1);
            

            //把字符串s1以“,”分割的形式,依次存入str2数组里。
            string[] str2 = s1.Split(',');
            for (int i = 0; i < str2.Length; i++)
            {
                Console.Write("str2[{0}]={1} ", i, str2[i]);
            }
            Console.WriteLine();


            //数组简单统计(平均值)此时必须保证数组是int类型的
            Console.WriteLine("--------------数组简单统计-------------");
            Console.WriteLine("sum(a)={0}", a.Sum());
            Console.WriteLine("average(a)={0}", a.Average());

            Console.WriteLine();

            //数组复制、排序
            Console.WriteLine("--------------数组复制、排序-------------");
            int[] s11 = new int[] { 4, 5, 3, 1, 2 };
            int[] s12 = new int[3]  ;
            Array.Copy(s11,0,s12,0,3);
            //把s11里从第s11[0]开始的往后3个元素,复制到s12从s12[0]开始里面

            for (int i = 0; i < s12.Length; i++)
            {
                Console.WriteLine("s12[{0}]={1}",i,s12[i]);
            }

            

            Array.Sort(s11);//对s11排序
            Console.WriteLine("升序排列:{0}", string.Join(" ", s11));
            Array.Reverse(s11);
            Console.WriteLine("逆序排列:{0}", string.Join(" ",s11 ));

            Console.WriteLine();

            //类型转化
            Console.WriteLine("--------------类型转换-------------");
            long m = 300000000;
            int n = 3000;
            m = n;
            n = (int)m;
            Console.WriteLine(n);
            Console.ReadLine();
        }
    }
}

在这里插入图片描述

数组简单统计
此时必须保证数组是int类型的

若不是,需要先转换:

for(int i = 0; i < array.length ; i++)
            {
                narray[i] = Convert.ToInt32(array[i]);
            }

Convert.ToInt32()和int.Parse()都可以数据转换个int类型,区别在于:

  1. Convert.ToInt32()将object类类型转换成int类型,例如:Convert.ToInt(textBox1.Test),int.Parse()将String类型转换成int类型,例如:int.Parse( textBox1.Test.ToString() )
  2. Convert.ToInt32(null)会返回0而不会产生任何异常,但int.Parse(null)则会产生异常。
  3. Parse就是把String转换成int,char,double…等,也就是*.Parse(string) 括号中的一定要是string.
    Convert可以提供多种类型的转换,也就是Convert.*()括号中可以为很多种类型(包括string).
数据类型之间的转换

在这里插入图片描述

将字符串转化为数组

//直接将字符串类型转换为数组类型
char[] arr= str.ToArray();
异常语句处理

例题:
创建一个包含 10 个元素的 int 一维数组,从键盘接收其值;当用户输入非法时,提示重新输入;计算一维数组中的元素平均值,并显示(保留小数点后4 位)

using Microsoft.Win32.SafeHandles;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace test
{
    class Program
    {
        static void Main(string[] args)
        {        
            int[] a = new int[10];
            int sum = 0;
            double ans;
            string n;
            for (int i = 0;i<10;i++)
            {
                Console.Write("请输入数组的第{0}个元素:",(i+1).ToString());
                n = Console.ReadLine();
                if (string.IsNullOrEmpty(n))
                {
                    Console.WriteLine("不可输入为空");
                    i--;
                }
                else
                {
                    try
                    {
                        a[i] = int.Parse(n);//将数字的字符串表示形式转换为他的等效32位有符号整数
                    }
                    catch
                    {
                        Console.WriteLine("非法输入");
                        i--;
                        continue;
                    }
                    sum += a[i];                 
                }              
            }
            ans = sum / 10.0;
            Console.WriteLine(ans.ToString("0.0000"));
            Console.ReadKey();           
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值