You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用数组实现欧姆定律计算器的流程控制及数组扩展用法咨询

C#欧姆定律计算器代码优化与数组应用方案

修改后的完整代码

using System;

namespace ENGR115_CourseProject_OctTerm
{
    internal class Program
    {
        static void Main(string[] args)
        {
            bool restartProgram;
            do
            {
                restartProgram = false;
                Console.WriteLine("Hello World!");
                Console.WriteLine(" Hello my name is Zachari Pryor ");
                Console.WriteLine(" This is the Course Programming Project: Ohm's Law ");
                Console.WriteLine(" The point of the term course project is to use C#");
                Console.WriteLine(" to have user solve Ohm's law using different variables of their choosing.");
                Console.WriteLine(" Press any key to move on");
                Console.ReadLine();
                Console.Clear();
                
                // 调用输入姓名流程,接收是否需要重启的信号
                restartProgram = enterName();
            } while (restartProgram);
        }

        static bool enterName()
        {
            Console.Write(" Enter your name: ");
            string name = Console.ReadLine();
            Console.WriteLine(" Hello it is very nice to meet you " + name);
            Console.WriteLine(" Are you ready to use C# to solve Ohm's Law (y or n) ? ");
            string response = Console.ReadLine().Trim().ToLower();
            if (response != "y")
            {
                Console.WriteLine("Okay, maybe next time!");
                return false;
            }
            Console.WriteLine(" Great!!, well then lets get started.Click enter");
            Console.ReadLine();
            Console.Clear();

            // 处理计算流程,接收操作选择
            int actionChoice;
            do
            {
                Equation();
                actionChoice = GetUserActionChoice();
                if (actionChoice == 0)
                {
                    Console.Clear();
                }
                else if (actionChoice == 2)
                {
                    Console.Clear();
                    return true; // 返回true告诉Main方法需要重启程序
                }
            } while (actionChoice == 0);

            return false; // 退出程序
        }

        static void Equation()
        {
            Console.Write("What would you like to find? V,I, or R:");
            string unitToFind = Console.ReadLine().Trim().ToUpper();
            
            // 用数组存储合法的单位选项,方便验证
            string[] validUnits = { "V", "I", "R" };
            if (!Array.Exists(validUnits, u => u == unitToFind))
            {
                Console.WriteLine("You need to enter either V, I or R.");
                return;
            }

            double V = 0, I = 0, R = 0;
            switch (unitToFind)
            {
                case "V":
                    Console.WriteLine("Enter the Resistance as a decimal.");
                    while (!double.TryParse(Console.ReadLine(), out R))
                        Console.WriteLine("Invalid input, please enter a decimal number.");
                    Console.WriteLine("Enter the Amperage as a decimal number");
                    while (!double.TryParse(Console.ReadLine(), out I))
                        Console.WriteLine("Invalid input, please enter a decimal number.");
                    V = R * I;
                    Console.WriteLine($"Voltage is: {V} Volts");
                    break;
                case "I":
                    Console.WriteLine("Enter the Voltage as a decimal number");
                    while (!double.TryParse(Console.ReadLine(), out V))
                        Console.WriteLine("Invalid input, please enter a decimal number.");
                    Console.WriteLine("Enter the Resistance as a decimal number");
                    while (!double.TryParse(Console.ReadLine(), out R))
                        Console.WriteLine("Invalid input, please enter a decimal number.");
                    I = V / R;
                    Console.WriteLine($"Amperage is: {I} Amps");
                    break;
                case "R":
                    Console.WriteLine("Enter the Voltage as a decimal number");
                    while (!double.TryParse(Console.ReadLine(), out V))
                        Console.WriteLine("Invalid input, please enter a decimal number.");
                    Console.WriteLine("Enter the Amperage as a decimal number");
                    while (!double.TryParse(Console.ReadLine(), out I))
                        Console.WriteLine("Invalid input, please enter a decimal number.");
                    R = V / I;
                    Console.WriteLine($"Resistance is: {R} Ohms");
                    break;
            }
        }

        static int GetUserActionChoice()
        {
            int[] validActions = { 0, 1, 2 };
            int choice;
            do
            {
                Console.WriteLine("\nPlease enter your choice:");
                Console.WriteLine("0 - Solve another Ohm's Law problem");
                Console.WriteLine("1 - Quit the program");
                Console.WriteLine("2 - Restart the entire program");
            } while (!int.TryParse(Console.ReadLine(), out choice) || !Array.Exists(validActions, a => a == choice));

            return choice;
        }
    }
}

流程控制逻辑说明

  1. 数组结合布尔值实现流程控制

    • 用int[] validActions = { 0, 1, 2 }存储合法的操作选项,通过Array.Exists快速验证用户输入是否符合要求,避免冗余的if-else判断。
    • Main方法外层用do-while循环,配合restartProgram布尔变量实现程序重启:当用户选择2时,enterName方法返回true,触发Main循环重新执行,完成程序重启。
    • enterName方法内部用do-while循环处理用户选择0的情况,重复调用Equation方法;选择1则退出循环,返回false终止程序;选择2则返回true触发Main循环重启。
  2. 输入验证优化

    • 在Equation方法中,用string[] validUnits = { "V", "I", "R" }存储合法的单位选项,通过Array.Exists验证用户输入,代码更简洁易维护。

数组在程序其他模块的应用方案

1. 存储计算历史记录

用数组(或泛型列表)存储每次计算的结果,方便用户查看历史:

// 定义全局列表存储历史记录
static List<string> calculationHistory = new List<string>();

// 在Equation方法计算完成后添加记录
calculationHistory.Add($"Calculated {unitToFind} = {(unitToFind == "V" ? V : unitToFind == "I" ? I : R)} ({V}V, {I}A, {R}Ω)");

// 添加查看历史的功能
static void ViewHistory()
{
    Console.WriteLine("\nCalculation History:");
    for (int i = 0; i < calculationHistory.Count; i++)
    {
        Console.WriteLine($"{i+1}. {calculationHistory[i]}");
    }
}

2. 统一存储输入提示信息

把不同场景的提示信息存入数组,减少重复代码,方便统一修改:

static string[] inputPrompts = {
    "Enter the Voltage as a decimal number",
    "Enter the Amperage as a decimal number",
    "Enter the Resistance as a decimal number"
};

// 使用时直接调用数组元素
Console.WriteLine(inputPrompts[0]);

3. 存储公式与单位对应关系

用二维数组存储欧姆定律的公式和单位,便于扩展或动态展示:

static string[,] ohmsLawFormulas = {
    { "V", "Voltage", "V = R * I" },
    { "I", "Amperage", "I = V / R" },
    { "R", "Resistance", "R = V / I" }
};

// 展示公式说明
static void ShowFormulas()
{
    Console.WriteLine("\nOhm's Law Formulas:");
    for (int i = 0; i < ohmsLawFormulas.GetLength(0); i++)
    {
        Console.WriteLine($"{ohmsLawFormulas[i,0]} ({ohmsLawFormulas[i,1]}): {ohmsLawFormulas[i,2]}");
    }
}

内容的提问来源于stack exchange,提问作者Zachari Pryor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 01:50:31