即使未分配变量,C# 代码也会执行

C# code executes even when variable not assigned

您可能从我的问题中看出,我对编码还很陌生。我正在尝试制作一个计算器来计算物理学中使用的一些公式。但是,代码 运行 在用户有时间输入 A 的值之前是公式,至少在这个例子中是这样。这是示例:

case "f = ma":
    Console.WriteLine("Type the value for M in KG:");
    var FM = Console.Read();
    Console.WriteLine("Type the value for A in M/S:");
    var FA = Console.Read();
    var FMARes = FM * FA;
    Console.WriteLine("Your answer (in Newtowns) is " + FMARes);
break;

如何检查变量A是否已经赋值,并且只有运行变量赋值后的公式?谢谢

您需要使用 ReadLine 而不是 Read。您还需要在底部执行另一个 ReadLine,以便用户可以看到结果。并且...您应该验证用户输入的是有效数字。这可以重构一点以避免重复代码 - 等等 - 但看看这是否适合你!祝你好运!!

    static void Main(string[] args)
    {
        double fm;
        double fa;

        // Use ReadLine instead of Read 
        Console.WriteLine("Type the value for M in KG:");
        var input = Console.ReadLine();

        // Now you need to cast it to a double - 
        // -- but only if the user entered a valid number 
        if (!double.TryParse(input, out fm))
        {
            Console.WriteLine("Please enter a valid number for M");
            Console.ReadLine(); 
            return; 
        }

        Console.WriteLine("Type the value for A in M/S:");
        input = Console.ReadLine();
        if (!double.TryParse(input, out fa))
        {
            Console.WriteLine("Please enter a valid number for A");
            Console.ReadLine();
            return; 
        }

        // Now we have valid values for fa and fm 
        // It's a better programming practice to use the string format 
        // intead of + here... 
        Console.WriteLine($"Your answer (in Newtowns) is {fm * fa}");

        // You need another read here or the program will just exit
        Console.WriteLine("Press Enter to end the program");
        Console.ReadLine(); 
    }