public class Weight {
public static void main(String[] args) {
Weight test1 = new Weight(500.12345);
double test4kilo = test1.getKilograms();
double test4kilo3 = test1.getPounds();
double test4kilo4 = test1.getOunces();
System.out.println(+test4kilo+", "+test4kilo3+", "+test4kilo4);
}
double w;
public Weight(double p){
p = w;
}
public double getPounds(){
return w;
}
public double getKilograms(){
return w*0.45359237;
}
public double getOunces(){
return w*(1/16);
}
}
每当我运行此代码时,它会打印“0.0,0.0,0.0”,这不是方法中计算的正确答案。谁能告诉我为什么会这样?谢谢!
答案 0 :(得分:3)
变化
/edx/bin/pip.edxapp install -e git+https://github.com/edx/XBlock.git@named-release/birch#egg=xblock
到
public Weight(double p){
p = w;
}
您需要设置public CopyOfTest1(double p){
this.w=p;
}
<强>输出强>
w
答案 1 :(得分:1)
作业从右到左
public Weight(double p) {
w = p;
}
答案 2 :(得分:0)
getOunces()
错了。当你将磅转换为盎司时,你应该乘以16而不是除以。
应该是:
public double getOunces() {
return w*16;
}
除此之外,修复构造函数中的拼写错误,以便将传递的权重存储在对象中:
public Weight(double p){
w = p;
}
您将获得正确的输出:
226.85218097807652, 500.12345, 8001.9752
答案 3 :(得分:0)
p = w;
应为w = p;
答案 4 :(得分:0)
不正确:
public Weight(double p){
p = w;
}
应该是:
public Weight(double p){
w = p; //Chnaged
}
你错配了变量分配。
答案 5 :(得分:0)
在构造函数中,您错误地等同于。这样做:
public Weight(double p){
w=p;
}
答案 6 :(得分:0)
您需要在构造函数中更改代码
使用它:
public Weight(double p)
{
w = p;
}
你得到了这个问题,因为你给的是p = w的值 并且w的初始值为0 所以你到处都是0 , 右边的值进入左变量