我是C#的新手,正在尝试弄清楚如何编写简单的代码来执行基本计算。我试图编写管道直径代码,一切似乎都很好,但结果是NaN。
由于我怀疑存在问题,因此我尝试更改变量声明的位置。我也尝试了static
关键字,但没有成功。
这是代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Pipe_Sizing
//This simple code is intended to calculate diameter of the pipe after getting flow and velcity values from the user
{
class Program {
//This method is created to read input from users and convert it to number
static void readnum(string inp, double num) {
inp = Console.ReadLine();
while ((num = double.Parse(inp)) < 0) {
Console.WriteLine("Sorry, you need value in digits");
inp = Console.ReadLine();
}
Console.WriteLine(num);
}
static string flo;
static double flox;
static string vel;
static double velx;
static void Main()
{
// Get the Flow value from thre user
Console.WriteLine("Please Enter the value of Flow in m3/hr");
readnum(flo, flox);
// Get the Velocity value from the user
Console.WriteLine("Please Enter the value of velcoty in m/s");
readnum(vel, velx);
double dd = (4 * flox) / (3.14 * velx);
double d = Math.Sqrt(dd);
Console.WriteLine("The diameter required for the pipe is " + d);
Console.ReadLine();
}
}
}
如何获取数字结果?
答案 0 :(得分:0)
方法readnum不返回任何内容。 readnum的参数(inp和num)是该方法的局部变量-更改其值对方法外部无效。因此,在Main方法中,变量flox和velx仍将具有默认值0.0。更改readnum,使其返回从用户输入解析的num。
答案 1 :(得分:0)
您的代码中有很多大数字
static void readnum(string inp, double num)
这没有做您想做的事情(我假设):double是一个值Type,表示它是通过值而不是通过引用传递的:您的代码将修改局部(为readnum方法)。同样适用于字符串inp:即使string是引用类型,它在此上下文中也可以用作值类型(有关此Google字符串c#不可变的更多信息) 在Main中调用readnum时,您传递的变量不会被修改
num = double.Parse(inp)
如果输入字符串不可转换为双精度(与int,date等的Parse方法相同),则Parse将引发异常。您可能要使用TryParse
并在继续之前检查它的返回值
static double flox;
static double velx;
实际上,您不需要使这些变量静态(甚至没有类成员):只需在使用它们的函数的局部声明它们:变量的范围越大,就越难处理
static string flo;
static string vel;
与上述内容大致相同,实际上,您只需要在readnum
内使用局部变量
double dd = (4 * flox) / (3.14 * velx);
.Net有一个非常方便的Math.Pi,比3.14好得多
这可以是代码的更干净(也许正在工作,未经测试)版本:
using System;
using System.Text;
public class Program
{
//This method is created to read input from users and convert it to number
static double readnum()
{
string inp = Console.ReadLine();
double res;
while (!double.TryParse(inp, out res)) // add check for negative value
{
Console.WriteLine("Sorry, you need value in digits");
inp = Console.ReadLine();
}
Console.WriteLine(res);
return res;
}
public static void Main()
{
// Get the Flow value from thre user
Console.WriteLine("Please Enter the value of Flow in m3/hr");
double flox = readnum();
// Get the Velocity value from the user
Console.WriteLine("Please Enter the value of velcoty in m/s");
double velx = readnum();
double dd = (4 * flox) / (Math.PI * velx); //
double d = Math.Sqrt(dd);
Console.WriteLine("The diameter required for the pipe is " + d);
Console.ReadLine();
}
}