尝试返回语句时收到错误

时间:2017-06-22 15:38:53

标签: c# visual-studio int return

为什么当我尝试返回语句时它显示not all code paths return a value错误 enter image description here

实际上我想要返回这个

public int multiplication(int num, int starting, int ending)
        {
            for(int i=starting; i<=ending; i++)
            {
                return (num+int.Parse("x")+starting+int.Parse("=")+(num*starting));
            }
        }

1 个答案:

答案 0 :(得分:2)

您的代码存在太多问题:

  1. starting > ending时应该返回什么方法:编译时错误
  2. "x"不是有效整数运行时异常
  3. 您似乎不想this,方法应为static
  4. 您真的想要退回int,而不是string吗?
  5. for(立即return)中的if等于public int multiplication(int num, int starting, int ending) { for(int i=starting; i<=ending; i++) { return (num+int.Parse("x")+starting+int.Parse("=")+(num*starting)); } }

        using System.Linq;
    
        ...
    
        public static string multiplication(int num, int starting, int ending) {
          return string.Join(Environment.NewLine, Enumerable
            .Range(starting, ending - starting + 1)
            .Select(i => $"{num} x {i} = {num * i}"));
        }
    
        ...
    
        Console.Write(multiplication(3, 5, 7));
    
  6. 我建议你真的想要这样的东西:

    3 x 5 = 15
    3 x 6 = 18
    3 x 7 = 21
    

    结果:

    bundle.js