2012-03-06 29 views
0

即时消息试图做的是让程序运行第一组数字。然后将输出用作'X'。所以它看起来像这样 Tnew = Told - m(Told - Tair) Told是Tnew的最后一个方程。Java程序中的递归需要重复上一个数字

ex. new = old +6 
old = 7 
new = 13 
new = 13 +6 
repeat 

继承人的代码; 包装heatloss;

/** 
* 
* @author Eric Franzen 
*/ 
public class HeatLoss { 

    public static void heatloss(double x, double m, double a) { 
     double heatloss = x - m * (x - a); 

     if (x < 55) { 
      System.out.println("potatoe too cold"); 
     } 
     else { 

      System.out.println(heatloss); 
      heatloss(x,m,a); 
      x = heatloss; 
     } 
    } 


    public static void main(String[] args) { 

     heatloss(80, .01515 ,25); 

    } 

}

好了,所以我改变了代码看起来像这样:

public static double heatloss(double x, double m, double a) { 
    double heatloss = x - m * (x - a); 

    if (x < 55) { 
     System.out.println("potatoe too cold"); 
     return heatloss; 
    } 
    else { 
     System.out.println(heatloss); 
     x = heatloss(x,m,a); 
     return heatloss; 
    } 
} 

但我在行

x = heatloss(x,m,a); 

那“的赋值为得到一个错误没用过。”我不确定这是什么意思? X在程序中明确使用。

+0

有问题吗? – 2012-03-06 03:39:03

回答

2

为了让一个递归方法调用另一个方法(例如存储在本地变量中的数据)内的数据,您需要以某种方式将该数据从第二次递归调用转换为第一次。在这种情况下,您可能需要考虑使heatloss方法返回heatloss局部变量的值。例如:

public static double heatloss(double x, double m, double a) { 
    double heatloss = x - m * (x - a); 

    if (x < 55) { 
     System.out.println("potatoe too cold"); 
     return /* put something here */ 
    } 
    else { 
     System.out.println(heatloss); 
     x = heatloss(x,m,a); 
     return /* put something here */ 
    } 
} 

通过在适当的填补空白(我不知道你会怎么做,在这里,因为我不熟悉你解决特定问题),你应该能够将深层呼叫中的信息通知上层呼叫。

希望这会有所帮助!

+0

我调整了代码,以适应您的建议。我有一个不知道如何解决的不同错误。我把它贴在上面。 – enrique2334 2012-03-06 04:01:18

0
/** 
* 
* @author Eric Franzen 
*/ 
public class HeatLoss { 

    public static void heatloss(double x, double m, double a) { 
     double heatloss = x - m * (x - a); 

     if (x < 55) { 
      System.out.println("potatoe too cold"); 
     } 
     else { 

      System.out.println(heatloss); 
      x = heatloss; 
      heatloss(x,m,a); 
     } 
    } 


    public static void main(String[] args) { 

     heatloss(80, .01515 ,25); 

    } 
} 
+0

在你的程序中,你用x的旧值调用heatloss。我在ur else子句中调换了两个语句。现在它返回Potatoe太冷了。 – Teja 2012-03-06 03:42:50

0
 heatloss(x,m,a); 
     x = heatloss; 

你让相信heatloss方法和heatloss变量在某种程度上是相关的错误。他们完全不相关。当heatloss该方法返回其值时,您必须将该返回值分配给某些内容(如果确实打算使用该值)。

你应该“玩电脑”,并用铅笔和纸片,在运行程序时发生的操作。这会让你更好地理解正在发生的事情。这不是魔术 - 它只是一个简单的“命令式”语言,每一步都使用以前(及时)步骤中发生的结果。