gpt4 book ai didi

java - 编写一个程序,在给定以下条件的情况下计算所有数字的平方和?

转载 作者:太空狗 更新时间:2023-10-29 22:50:10 25 4
gpt4 key购买 nike

Given two numbers n1 and n2 such that n2>n1, find sum of squares of all numbers from n1 to n2 (including n1 and n2).

我的方法:

我尝试使用从 n1 迭代到 n2 的 for 循环来解决问题,但我得到了错误的答案

下面是我的代码函数:

public int computeSumofSquares (int n1, int n2) 
{
int sum=0;
if(n2>n1)
{
for(int i=n1;i<=n2;i++)
{
sum=((sum)+(n1*n1));
}
}
return sum;
//write your code here

}

对于输入

Parameters  Actual Output   Expected Output
'8' '10' 192 245

最佳答案

您在每次迭代中对 n1 求平方。相反,您应该平方 i。作为 sum=((sum)+(i*i)); 的缩写形式,您可以编写 sum += i * i;

关于java - 编写一个程序,在给定以下条件的情况下计算所有数字的平方和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33370140/

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