给我一段c#写的专家系统
时间: 2023-10-18 21:12:06 浏览: 39
以下是一个简单的C#专家系统示例,用于诊断某些疾病:
```csharp
using System;
using System.Collections.Generic;
class Symptom
{
public string Name { get; set; }
public bool HasSymptom { get; set; }
}
class Disease
{
public string Name { get; set; }
public Func<List<Symptom>, bool> CheckSymptoms { get; set; }
}
class ExpertSystem
{
private List<Symptom> symptoms = new List<Symptom>();
private List<Disease> diseases = new List<Disease>();
public void AddSymptom(Symptom symptom)
{
symptoms.Add(symptom);
}
public void AddDisease(Disease disease)
{
diseases.Add(disease);
}
public void Run()
{
Console.WriteLine("Please answer the following questions with 'yes' or 'no':");
foreach (var symptom in symptoms)
{
Console.Write($"Do you have {symptom.Name}? ");
string answer = Console.ReadLine().ToLower();
if (answer == "yes")
{
symptom.HasSymptom = true;
}
}
List<Disease> possibleDiseases = new List<Disease>();
foreach (var disease in diseases)
{
if (disease.CheckSymptoms(symptoms))
{
possibleDiseases.Add(disease);
}
}
if (possibleDiseases.Count == 0)
{
Console.WriteLine("No diseases match your symptoms.");
}
else if (possibleDiseases.Count == 1)
{
Console.WriteLine($"You may have {possibleDiseases[0].Name}.");
}
else
{
Console.WriteLine("You may have one of the following diseases:");
foreach (var disease in possibleDiseases)
{
Console.WriteLine(disease.Name);
}
}
}
}
class Program
{
static void Main(string[] args)
{
ExpertSystem expertSystem = new ExpertSystem();
// Define symptoms
Symptom cough = new Symptom() { Name = "a cough" };
Symptom fever = new Symptom() { Name = "a fever" };
Symptom rash = new Symptom() { Name = "a rash" };
// Define diseases
Disease commonCold = new Disease() { Name = "the common cold" };
commonCold.CheckSymptoms = (symptoms) =>
{
return symptoms.Exists(s => s.Name == cough.Name && s.HasSymptom) &&
symptoms.Exists(s => s.Name == fever.Name && s.HasSymptom);
};
Disease measles = new Disease() { Name = "measles" };
measles.CheckSymptoms = (symptoms) =>
{
return symptoms.Exists(s => s.Name == rash.Name && s.HasSymptom);
};
// Add symptoms and diseases to expert system
expertSystem.AddSymptom(cough);
expertSystem.AddSymptom(fever);
expertSystem.AddSymptom(rash);
expertSystem.AddDisease(commonCold);
expertSystem.AddDisease(measles);
// Run expert system
expertSystem.Run();
Console.ReadLine();
}
}
```
在上面的代码中,症状和疾病都是用类表示的。专家系统询问用户有关症状的问题,并记录用户的回答。然后,它将检查所有可能的疾病,并显示匹配用户症状的疾病。