gpt4 book ai didi

java - Android 平方根计算错误

转载 作者:太空宇宙 更新时间:2023-11-04 12:11:05 28 4
gpt4 key购买 nike

我想制作一个使用 Heron 算法计算平方根的 Java 应用程序。但是当我输入 9 时,它会在屏幕上打印 2.777777910232544 。当我输入 1 时,它会打印 1。现在我不知道是否我写错了代码,或者我不了解 Java 中的 float 。

这是我的代码:

public class MainActivity extends AppCompatActivity {

float length1;
float width1;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView mainOutput = (TextView) findViewById(R.id.mainOutput);
final EditText mainInput = (EditText) findViewById(R.id.mainInput);
final Button wurzel2 = (Button) findViewById(R.id.wurzel2);

assert wurzel2 != null;
wurzel2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

for(int i = 0; i < 20; i++) {
float inputNumber = Integer.parseInt(mainInput.getText().toString());
length1 = 1;
width1 = inputNumber / length1;
float length2 = (length1 + width1) / 2;
float width2 = inputNumber / length2;
length1 = length2;
width1 = width2;
}
double wurzel = length1 / width1;
mainOutput.setText(String.valueOf(wurzel));
}
});
}
}

最佳答案

我编写了 Heron 算法的非 Android Java 实现,该实现源自 https://en.wikipedia.org/wiki/Methods_of_computing_square_roots 中显示的算法公式。

public class MyClass {
public static void main(String[] args) {
float x = 9;
System.out.println(heron(x));
}

static float heron(float s) {
float x = (float) 1.0; // initial approximation of result
for (int i = 0; i < 20; i++) {
float sDivX = s / x;
x = (x + sDivX) / 2;
// remove this line in production, this is just to watch progress
System.out.println(String.valueOf(x));
}
return x;
}
}

你的代码在循环内有length1=1(你的length1相当于我的x),所以从一个迭代到另一个迭代,它没有取得任何进展。

x = s/(float)2 可能是比 1 更好的初始估计,特别是对于较大的值。对于较小的输入值,20 次迭代可能有点过大。

关于java - Android 平方根计算错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39858346/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com