[英]Function with parameters in c#?
我正在嘗試創建一個名為“ compNumbers”的函數,該函數需要2個雙數。 如果兩個數字相等,則它們應返回0,如果第一個參數大於第二個參數,則應返回1,如果第二個參數大於第一個參數,則應返回-1。
這是我對這個問題的嘗試:
static double compNumbers(double x, double y)
{
if (x == y)
{
return 0;
}
else if (x > y)
{
return 1;
}
else if (y > x)
{
return -1;
}
}
static void Main(string[] args)
{
double a = 0, b = 0;
compNumbers(a,b);
Console.ReadKey();
}
我遇到的錯誤是:
描述說:“ Program.compNumbers(double,double):並非所有代碼路徑都返回值”。
另外,由於我是編程新手,因此將“輸入,處理,輸出”代碼放在哪里? 我對從哪里開始感到困惑...
感謝您的幫助!
例如,如果x
或y
值為double.NaN
,則所有條件都將返回false
,因此您將到達函數的結尾,並且需要返回somethig:
static double compNumbers(double x, double y)
{
if (x == y)
{
return 0;
}
else if (x > y)
{
return 1;
}
else if (y > x)
{
return -1;
}
return double.NaN
}
有關double.NaN
值的更多信息: https : double.NaN
= double.NaN
要比較雙CompareTo
值,請使用特殊方法CompareTo
:
x.CompareTo(y);
static double compNumbers(double x, double y)
{
return x.CompareTo(y);
}
您遇到的問題是,如果所有其他條件均為false,則沒有任何回報。
由於“ x不等於y”和“ x不大於y”的唯一選擇是“ y必須大於x”,因此如果要刪除最后一個,並保存幾行代碼,只是返回-1。
static double compNumbers(double x, double y)
{
if (x == y)
{
return 0;
}
else if (x > y)
{
return 1;
}
return -1;
}
首先,在這種情況下,您不必將方法聲明為double
因為您只需要一個int
!
其次,當所有條件都為假時,您必須返回一些東西!
static int? CompNumbers(double x, double y) //int? is nothing more than nullable int
{
if (x == y)
{
return 0;
}
else if (x > y)
{
return 1;
}
else if (y > x)
{
return -1;
}
return null; //this is the return value you have give !!
}
static void Main(string[] args)
{
double a = Convert.ToDouble(Console.ReadLine());//taking input from user
double b = Convert.ToDouble(Console.ReadLine());//taking input from user
int? result = CompNumbers(a, b);//assigning result to the return value of CompNumbers and int? is nothing more than nullable int
if (result == 0)
{
Console.WriteLine("The Method returned 0");
}
else if (result == 1)
{
Console.WriteLine("The Method returned 1");
}
else if(result == -1)
{
Console.WriteLine("The Method returned -1");
}
Console.ReadKey();
}
這可能會有所幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.