一、任务一:使用字典存储0~9的数字对应的大写文字

(1)提示用户输入一个不超过三位的数,提供一个方法,
(2)返回数的大写。例如:306,返回 叁零陆


二、代码解析

1. 字典初始化

Dictionary dic = new Dictionary();
dic.Add(0, "零");
dic.Add(1, "壹");
// ... 其他数字映射

(1)使用Dictionary建立阿拉伯数字到中文大写的映射关系

(2)键值对形式存储,便于快速查找

2. 数字位数分离算法

int bai = num / 100;        // 获取百位数
int shi = num % 100 / 10;   // 获取十位数
int ge = num % 10;          // 获取个位数

(1)百位:通过整除100获得

(2)十位:先取模100得到后两位数,再整除10

(3)个位:直接取模10获得

3. 条件分支处理

if (bai != 0)           // 处理三位数
else if (shi != 0)      // 处理两位数
else                    // 处理一位数

(1)根据数字的位数选择不同的处理逻辑

(2)确保各种位数情况都能正确处理

三、完整代码

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace 进阶测试
{
class Program
{
public static string GetType(int num)
{
Dictionary dic = new Dictionary();
dic.Add(0, "零");
dic.Add(1, "壹");
dic.Add(2, "贰");
dic.Add(3, "叁");
dic.Add(4, "肆");
dic.Add(5, "伍");
dic.Add(6, "陆");
dic.Add(7, "柒");
dic.Add(8, "捌");
dic.Add(9, "玖");
string value;
int bai = num / 100;
int shi = num % 100 / 10;
int ge = num % 10;
if (bai!=0)//三位数
{
value = "" + dic[bai] + dic[shi] + dic[ge];
}
else if(shi!=0)//两位数
{
value = "" + dic[shi] + dic[ge];
}
else//一位数
{
value = "" + dic[ge];
}
return value;
}
static void Main(string[] args)
{
Console.WriteLine("请输入一个不超过三位的数:");
Console.WriteLine("您输入的值为:"+GetType(int.Parse(Console.ReadLine())));
}
}
}

四、任务二:计算每个字母出现的次数

(1)使用字典存储
(2)最后遍历整个字典,不区分大小写


五、代码分析

1. 核心方法:DealWithString

public static void DealWithString(string str)
{
str = str.ToLower();  // 统一转换为小写,不区分大小写
Dictionary dic = new Dictionary();
// 遍历字符串的每个字符
for (int i = 0; i < str.Length; i++)
{
if (dic.ContainsKey(str[i]))
{
dic[str[i]]++;  // 已存在字符,计数+1
}
else
{
dic.Add(str[i], 1);  // 新字符,初始化为1
}
}
}

2. 字典操作详解

字典的初始化:

Dictionary dic = new Dictionary();

(1)键(Key): char 类型,存储字符

(2)值(Value): int 类型,存储该字符出现的次数

字符统计逻辑:

if (dic.ContainsKey(str[i]))  // 检查字符是否已存在
{
dic[str[i]]++;           // 存在则计数增加
}
else
{
dic.Add(str[i], 1);      // 不存在则添加新条目
}

3. 结果输出

foreach (char c in dic.Keys)
{
Console.WriteLine("{0}:{1}个", c, dic[c]);
}

(1)遍历字典中的所有键(字符)

(2)输出每个字符及其出现次数


六、完整代码

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace 进阶测试
{
class Program
{
public static void DealWithString(string str)
{
str=str.ToLower();
Dictionary dic = new Dictionary();
for (int i = 0; i < str.Length; i++)
{
if (dic.ContainsKey(str[i]))
{
dic[str[i]]++;
}
else
{
dic.Add(str[i], 1);
}
}
Console.WriteLine("您输入的字符串识别字符以及相应的数量为:");
foreach (char c in dic.Keys)
{
{
Console.WriteLine("{0}:{1}个", c, dic[c]);
}
}
}
static void Main(string[] args)
{
Console.Write("请输入需要检查的字符串:");
string str = Console.ReadLine();
Console.WriteLine("您输入的字符串为:{0}",str);
DealWithString(str);
}
}
}
posted on 2025-10-10 20:30  ycfenxi  阅读(4)  评论(0)    收藏  举报