gpt4 book ai didi

java - 阶乘计算问题

转载 作者:行者123 更新时间:2023-12-01 20:03:00 25 4
gpt4 key购买 nike

我创建了一个 Android 应用程序来计算输入数字的阶乘。我的代码是:

void factorial(int x){
if(x>=0){
BigInteger res= new BigInteger("1");
for(int i=x; i>1; i--){
res = res.multiply(BigInteger.valueOf(i));
}

TextView text = (TextView)findViewById(R.id.resultTextView);
text.setText(res.toString());
}
}

它可以工作,但是当我尝试计算阶乘 80.000 或更多时,应用程序卡住了一会儿然后退出,重新加载 Android 的图形“桌面”界面。电脑运行同一段代码不会产生任何问题。如何修复我的应用程序以计算这些值而不是自行终止?

提前致谢。

最佳答案

试试这个:

private class FactCalculator extends AsyncTask<Void, Void, BigInteger> {
int number = 0;

public FactCalculator(int i) {
this.number =i;
}

@Override
protected BigInteger doInBackground(final Void... params){
try{
if(number>=0) {
BigInteger res = new BigInteger("1");
for (int i = number; i > 1; i--) {
res = res.multiply(BigInteger.valueOf(i));
}
return res;
}
} catch(Exception e){
e.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(final BigInteger result) {
if (result != null) {
TextView text = (TextView)findViewById(R.id.resultTextView);
text.setText(result.toString());
}
}
}

这样调用它:

new FactCalculator(80000).execute();

注意:- 正如其他人在评论中指出的那样,这可能是因为值太大,可能存在内存问题或保存在 String 或在 TextView 中,

关于java - 阶乘计算问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47833675/

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