您可能从我的问题中可以看出,我对编码非常陌生。我正在尝试制作一个可以计算物理中使用的一些公式的计算器。但是,代码至少在此示例中在用户没有时间输入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,并且仅在变量具有分配值之后才运行公式?谢谢。
答案 0 :(得分:1)
您需要使用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();
}