【问题标题】:C# Method DeclaringC# 方法声明
【发布时间】:2015-10-26 23:52:47
【问题描述】:
 public void GetPosNonZeroDouble()
 { 
     double x;

     Console.WriteLine("Enter The Length Of The Side");
     x = double.Parse(Console.ReadLine());
     if (x <= 0)
         Console.WriteLine("Error - input must be a non - zero positive number");
     else
         return x;

     x = double.Parse(Console.ReadLine());
 }

 static void ProcessSquare()
 {
     GetPosNonZeroDouble();
     double side;
     double answer;
     Console.WriteLine();
     side = double.Parse(Console.ReadLine());
     answer = Math.Pow(side, 2);

     Console.WriteLine("The Square Area is {0}", answer);
 }

我应该有一个“GetPosNonZeroDouble”,它需要像这样的图像:c#Question 我已经声明了这个方法,但我不确定我如何告诉 processSquare() 检查数字是否

【问题讨论】:

    标签: c# methods console


    【解决方案1】:

    您需要将方法设为静态,或者将其设为类的一部分并从类的实例中调用它。此外,您不能从 void 方法返回值。

    public static double GetPosNonZeroDouble()
    { 
        double x = 0;
    
        while (x <= 0)
        {
            Console.WriteLine("Enter The Length Of The Side");
            if (!double.TryParse(Console.ReadLine(), x) || x <= 0)
            {
                Console.WriteLine("Error - input must be a non - zero positive number");
            }
        }
        return x;
     }
    

    【讨论】:

      【解决方案2】:
      GetPosNonZeroDouble
      

      是您尝试从静态方法调用的实例方法,但您不能这样做。您需要创建 GetPosNonZeroDouble 所在类的实例,然后使用点表示法调用它。 看看here,你也应该尝试一些 C# 教程来帮助你。

      【讨论】:

        【解决方案3】:

        您似乎对一般方法没有经验。

        首先,我建议您查看官方 C# 文档中的方法: https://msdn.microsoft.com/en-us/library/vstudio/ms173114(v=vs.100).aspx

        例如,您的方法 GetPosNonZeroDouble() 不返回任何内容,但您尝试使用 return x; 返回一个值(这将导致编译器错误)。

        【讨论】:

          猜你喜欢
          • 2010-11-17
          • 1970-01-01
          • 1970-01-01
          • 2012-10-15
          • 1970-01-01
          • 2012-06-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多