2016-01-21 73 views
-6

我正在写一个程序使用的方法,我超级失去了。我的任务是here,但我无法弄清楚如何从一种方法获取值到另一种方法。现在我再澄清一点,我需要第二种方法中的值转移到主要方法,而不是特别的为我工作。我不知道如何返回值C#

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace Ch7Ex3a 
{ 
    public class Program 
    { 
     public void stuff() 
     { 

     } 
     static void Main(string[] args) 
     { 

      double length=0,depth=0,total=compute; 

      Console.Write("What is the length in feet? "); 
      length=Convert.ToDouble(Console.ReadLine()); 

      Console.Write("What is the depth in feet? "); 
      depth = Convert.ToDouble(Console.ReadLine()); 

      Console.WriteLine("${0}", total); 
      Console.ReadKey(); 
     } 

     static double compute(double length,double depth) 
     { 
      double total; 
      total = length*depth* 5; 
      return total; 

     } 


    } 
} 

谢谢你的时间我知道这不是最好的代码。

+0

你想达到什么目的?什么不正确? –

+0

'total = compute'永远不会编译。首先阅读关于C#编程的MSDN文章作为起点。 –

+0

该任务需要您创建一个新班级。该类应位于Main()所在的Program类后面。程序类的所有方法必须是静态的。用户生成类的方法不需要是静态的。 – jdweng

回答

1

所有您需要做的是加入这一行同时读取lenght和深度值后:

double total = compute(length, depth); 

你告诉那个total将从方法计算什么return

请记住将参数发送给m​​ethod,并且在读取两个值后始终调用该方法,否则在调用方法时它们将为零。你的代码应该是这样的:

static void Main(string[] args) 
{ 
    double length = 0, depth = 0; 

    Console.Write("What is the length in feet? "); 
    length = Convert.ToDouble(Console.ReadLine()); 

    Console.Write("What is the depth in feet? "); 
    depth = Convert.ToDouble(Console.ReadLine()); 

    double total = compute(length, depth); 

    Console.WriteLine("${0}", total); 
    Console.ReadKey(); 
} 
1

你调用一个方法与参数如下:

var length = 4; // example values 
var depth = 8; // example values 

var toal = compute(length, depth); 

在这之后你的变量total的值将160

4

只要调用方法:

Console.WriteLine("${0}", compute(length,depth)); 

或者:

double length = 0, depth = 0, total = 0; 
total = compute(length, depth); 

然后:

Console.WriteLine("${0}", total); 

或者在C#6:

Console.WriteLine($"{total}"); 
1

您可以直接在结果使用

Console.WriteLine("${0}", compute(length,depth)); 

打印到控制台通过这样做这样你不必声明一个附加变量total所以声明将如下所示,

double length=0,depth=0; 
相关问题