3 回答

TA貢獻(xiàn)1744條經(jīng)驗(yàn) 獲得超4個(gè)贊
當(dāng)您的函數(shù)返回值時(shí),這意味著您需要從每個(gè) if..else 塊中返回值return double value。
在這里,您沒有從 else 塊返回任何值。您需要從 else 塊返回雙精度值
else
{
Console.WriteLine("Please follow the specified input form (a^b).");
Console.ReadKey();
return Coefficient(); // This will call recursively same function. for recursion use return Coefficient() ;
//return 0; //If you don't want recursion, then comment above line and return 0
}
我寧愿重構(gòu)您的代碼以最小化Coefficient()方法中存在的代碼。就像是 ,
public static double Coefficient()
{
while (true)
{
string string1 = Console.ReadLine();
string[] stringArray = string1.Split('^');
double[] doubleArray = Array.ConvertAll(stringArray, double.Parse);
if (doubleArray.Length == 2)
{
double coefficient = Math.Pow(doubleArray[0], doubleArray[1]);
return coefficient;
}
else if (doubleArray.Length == 1)
{
return doubleArray[0];
}
Console.WriteLine("Please follow the specified input form (a^b).");
}
}

TA貢獻(xiàn)1808條經(jīng)驗(yàn) 獲得超4個(gè)贊
該錯(cuò)誤意味著至少一種流可能性不返回值,這是您案例中的最后一個(gè)“其他”。
最后一行應(yīng)該是:
return Coefficient();

TA貢獻(xiàn)1844條經(jīng)驗(yàn) 獲得超8個(gè)贊
我建議重新設(shè)計(jì)例程(我看不到遞歸的任何需要)。您可以實(shí)現(xiàn)一個(gè)循環(huán),以便在用戶輸入 ( Console.ReadLine()) 有效值之前一直詢問:
public static double Coefficient() {
while (true) {
string input = Console.ReadLine();
string[] items = input.Split('^');
if (items.Length == 1) {
if (double.TryParse(items[0], out double A))
return A; // One valid value
}
else if (items.Length == 2) {
if (double.TryParse(items[0], out double A) &&
double.TryParse(items[1], out double B))
return Math.Pow(A, B); // Two valid values
}
// Neither one valid value, nor two valid values pattern
Console.WriteLine("Please follow the specified input form (a^b).");
// No need in "Console.ReadKey();" - the routine will stop on Console.ReadLine()
}
}
小心,Double.Parse因?yàn)樗鼤?huì)在無效字符串上拋出異常"bla-bla-bla"(例如,如果用戶輸入);改用Double.TryParse。
- 3 回答
- 0 關(guān)注
- 170 瀏覽
添加回答
舉報(bào)