这是我的代码:
private double time = 0;
..............
..............
..............
public static double time(TreeNode<City> tree{
City A = tree.getCity();
if (tree.hasLeftChild()){
time += tree.getLeftChild().getCity().distance(A);
time(tree.getLeftChild());
}
if (tree.hasNextSibling()){
time += tree.getNextSibling().getCity().distance(A);
time(tree.getNextSibling());
}
return time;
}
我想计算一棵树旅行的总时间。然而,有一个大问题:名为time的字段必须是静态的,以便我可以在静态方法中使用它。但是,当它是静态的时,程序总是返回0.如何进行更改以计算树的总行进时间???
干杯。
答案 0 :(得分:0)
不进入变量属性的细节,我只会注意到你编写了一个返回变量的递归函数。我建议您实际使用该返回并执行必要的操作以在结尾处分配值。像
这样的东西public static double time(TreeNode<City> tree{
double thistime = 0.0;
City A = tree.getCity();
if (tree.hasLeftChild()){
thistime += tree.getLeftChild().getCity().distance(A);
thistime += time(tree.getLeftChild());
}
if (tree.hasNextSibling()){
thistime += tree.getNextSibling().getCity().distance(A);
thistime += time(tree.getNextSibling());
}
return thistime;
}
然后当你打电话时;
time = time(root);
printf("Time is %f, actual time should be %f\n",time,time(root));
最后的printf只是为了帮助弄清楚是否存在某种属性分配问题与函数中的错误相比。
代码应尽量避免在可能的情况下更新代码范围之外的变量。在转换为线程,信号处理,调试时,可以提高安全性,并且通常可以防止远距离的怪异行为。
我会在您的示例代码中注意到您显然在函数定义中缺少close-parent。