3 回答
![?](http://img1.sycdn.imooc.com/5458620000018a2602200220-100-100.jpg)
TA贡献1744条经验 获得超4个赞
当您的函数返回值时,这意味着您需要从每个 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
}
我宁愿重构您的代码以最小化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).");
}
}
![?](http://img1.sycdn.imooc.com/533e4c0500010c7602000200-100-100.jpg)
TA贡献1844条经验 获得超8个赞
我建议重新设计例程(我看不到递归的任何需要)。您可以实现一个循环,以便在用户输入 ( 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因为它会在无效字符串上抛出异常"bla-bla-bla"(例如,如果用户输入);改用Double.TryParse。
- 3 回答
- 0 关注
- 147 浏览
添加回答
举报