namespace SandwichCalories { class Program { static void Main(string[] args) { // sandwich ingredients and their associated calories Dictionary<string, int> ingredients = new Dictionary<string, int>() { { "Bread", 100 }, { "Ham", 150 }, { "Lettuce", 10 }, { "Tomato", 20 }, { "Mayonnaise", 50 }, { "Cheese", 120 } }; // prompt user for calorie range Console.Write("Enter minimum calories: "); int min_calories = int.Parse(Console.ReadLine()); Console.Write("Enter maximum calories: "); int max_calories = int.Parse(Console.ReadLine()); // calculate the minimum and maximum calories for the sandwich int min_sandwich_calories = 2 * ingredients["Bread"] + ingredients.Values.Min() * 2; int max_sandwich_calories = 2 * ingredients["Bread"] + ingredients.Values.Max() * 2; // check if the calorie range is valid if (max_calories < min_sandwich_calories) { Console.WriteLine("Sorry, it is impossible to create a sandwich within the given calorie range."); } else { // create the sandwich List<string> sandwich = new List<string> { "Bread", "Bread" }; int sandwich_calories = 2 * ingredients["Bread"]; while (sandwich_calories < min_calories) { // add random ingredient string ingredient = ingredients.Keys.ElementAt(new Random().Next(ingredients.Count)); sandwich.Add(ingredient); sandwich_calories += ingredients[ingredient]; } while (sandwich_calories <= max_calories) { // add random ingredient string ingredient = ingredients.Keys.ElementAt(new Random().Next(ingredients.Count)); // check if the ingredient is the same as the previous one if (sandwich.Count >= 3 && ingredient == sandwich[sandwich.Count - 2]) { continue; } sandwich.Add(ingredient); sandwich_calories += ingredients[ingredient]; // check if the sandwich is already at the maximum calorie limit if (sandwich_calories == max_sandwich_calories) { break; } } // add the last slice of bread sandwich.Add("Bread"); // print the sandwich and its total calories Console.WriteLine("Your sandwich: " + string.Join(", ", sandwich)); Console.WriteLine("Total calories: " + sandwich_calories); } } } } 改进代码
时间: 2024-04-02 14:36:30 浏览: 62
C#中static void Main(string[] args) 参数示例详解
以下是一些可能的改进,可以提高代码的可读性和可维护性:
1. 将常量和魔法数字(如2)抽象成变量或常量,以提高代码的可读性和可维护性。
2. 将一些重复的代码抽象成函数或方法,以减少代码的重复性。
3. 添加注释,以解释代码的功能和实现方式。
4. 将用户输入的代码放在try-catch块中,以捕获可能的异常。
5. 将随机数生成器抽象成一个单独的类,以便在测试时进行替换。
6. 将字典中的键和值封装为一个类,以提高代码的可读性和可维护性。
7. 添加单元测试,以确保代码的正确性和可靠性。
8. 使用LINQ查询和操作集合,以简化代码并减少重复性。
以下是改进后的代码:
using System;
using System.Collections.Generic;
using System.Linq;
namespace SandwichCalories
{
class Program
{
private const int BreadCalories = 100;
private const int MinSandwichCaloriesMultiplier = 2;
private const int MaxSandwichCaloriesMultiplier = 2;
private const int DefaultIngredientCalories = 0;
static void Main(string[] args)
{
// sandwich ingredients and their associated calories
var ingredients = new List<Ingredient>
{
new Ingredient("Bread", 100),
new Ingredient("Ham", 150),
new Ingredient("Lettuce", 10),
new Ingredient("Tomato", 20),
new Ingredient("Mayonnaise", 50),
new Ingredient("Cheese", 120)
};
// prompt user for calorie range
Console.Write("Enter minimum calories: ");
int minCalories;
int.TryParse(Console.ReadLine(), out minCalories);
Console.Write("Enter maximum calories: ");
int maxCalories;
int.TryParse(Console.ReadLine(), out maxCalories);
try
{
// calculate the minimum and maximum calories for the sandwich
int minSandwichCalories = CalculateMinSandwichCalories(ingredients);
int maxSandwichCalories = CalculateMaxSandwichCalories(ingredients);
// check if the calorie range is valid
if (maxCalories < minSandwichCalories)
{
Console.WriteLine("Sorry, it is impossible to create a sandwich within the given calorie range.");
}
else
{
// create the sandwich
List<string> sandwich = CreateSandwich(ingredients, minCalories, maxCalories);
// print the sandwich and its total calories
Console.WriteLine("Your sandwich: " + string.Join(", ", sandwich));
Console.WriteLine("Total calories: " + CalculateSandwichCalories(sandwich, ingredients));
}
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
}
private static int CalculateMinSandwichCalories(List<Ingredient> ingredients)
{
int minIngredientCalories = ingredients.Min(i => i.Calories);
return MinSandwichCaloriesMultiplier * BreadCalories + MinSandwichCaloriesMultiplier * minIngredientCalories;
}
private static int CalculateMaxSandwichCalories(List<Ingredient> ingredients)
{
int maxIngredientCalories = ingredients.Max(i => i.Calories);
return MaxSandwichCaloriesMultiplier * BreadCalories + MaxSandwichCaloriesMultiplier * maxIngredientCalories;
}
private static List<string> CreateSandwich(List<Ingredient> ingredients, int minCalories, int maxCalories)
{
List<string> sandwich = new List<string> { "Bread", "Bread" };
int sandwichCalories = MinSandwichCaloriesMultiplier * BreadCalories;
// add ingredients until minimum calorie limit is reached
while (sandwichCalories < minCalories)
{
Ingredient randomIngredient = GetRandomIngredient(ingredients);
sandwich.Add(randomIngredient.Name);
sandwichCalories += randomIngredient.Calories;
}
// add ingredients until maximum calorie limit is reached
while (sandwichCalories <= maxCalories)
{
Ingredient randomIngredient = GetRandomIngredient(ingredients);
// check if the ingredient is the same as the previous one
if (IsSameAsPreviousIngredient(sandwich, randomIngredient.Name))
{
continue;
}
sandwich.Add(randomIngredient.Name);
sandwichCalories += randomIngredient.Calories;
// check if the sandwich is already at the maximum calorie limit
if (sandwichCalories == CalculateMaxSandwichCalories(ingredients))
{
break;
}
}
// add the last slice of bread
sandwich.Add("Bread");
return sandwich;
}
private static Ingredient GetRandomIngredient(List<Ingredient> ingredients)
{
return ingredients[new Random().Next(ingredients.Count)];
}
private static bool IsSameAsPreviousIngredient(List<string> sandwich, string ingredient)
{
return sandwich.Count >= 3 && ingredient == sandwich[sandwich.Count - 2];
}
private static int CalculateSandwichCalories(List<string> sandwich, List<Ingredient> ingredients)
{
return sandwich.Sum(s => ingredients.FirstOrDefault(i => i.Name == s)?.Calories ?? DefaultIngredientCalories);
}
}
public class Ingredient
{
public string Name { get; set; }
public int Calories { get; set; }
public Ingredient(string name, int calories)
{
Name = name;
Calories = calories;
}
}
}
阅读全文