Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Loops 而循环条件推理、逻辑故障、返回平方和<;=n(我的第一个输入_Loops_While Loop_Logic_Conditional Statements_Reasoning - Fatal编程技术网

Loops 而循环条件推理、逻辑故障、返回平方和<;=n(我的第一个输入

Loops 而循环条件推理、逻辑故障、返回平方和<;=n(我的第一个输入,loops,while-loop,logic,conditional-statements,reasoning,Loops,While Loop,Logic,Conditional Statements,Reasoning,我在while循环的逻辑和推理方面遇到了问题,返回的是正数的和n,以及输入的和n的平方。请查看我的代码并在可能的情况下提供帮助,谢谢 这次演习是: /*编写一个简短的Java方法,该方法接受整数n并返回 小于或等于n的所有正整数的平方。 * */ 公共类ch1dot7 { 公共静态void main(字符串[]args) { 扫描仪输入=新扫描仪(System.in); int n,m=0,和=0; System.out.print(“请输入n:”的值); n=input.nextInt();

我在while循环的逻辑和推理方面遇到了问题,返回的是正数的和n,以及输入的和n的平方。请查看我的代码并在可能的情况下提供帮助,谢谢

这次演习是: /*编写一个简短的Java方法,该方法接受整数n并返回 小于或等于n的所有正整数的平方。 * */

公共类ch1dot7
{
公共静态void main(字符串[]args)
{
扫描仪输入=新扫描仪(System.in);
int n,m=0,和=0;
System.out.print(“请输入n:”的值);
n=input.nextInt();
System.out.println(“n当前为“+n”);
如果(n)
{
System.out.print(“请输入m的值(输入大于n的值以退出):”;
m=输入.nextInt();
if(m
您误解了作业。作业不要求您接受用户的输入。方法的唯一输入是
n

问题是要制作一个方法,它取一个整数n并返回所有小于n的正整数的平方和

public static int sumOfSquares(int n) {
    // here you can check if n is greater than 0

    int counter = 1;
    int sum = 0;
    while (counter < n) {
        // [ sum up the square of the counter ]
        counter++;
    }

    return n;
}
例如,如果n为5,则需要将小于5的数字的平方相加,即数字1到4,如下所示:

(1*1) + (2*2) + (3*3) + (4*4)

1 + 4 + 9 + 16 = 30
你的方法应该返回30

while
循环中,提示用户进行其他输入,并将其保存在变量
m
中。这是不需要的。不需要变量
m

当计数器变量小于n时,您的
while
循环应继续,并且每个循环中的计数器应递增。从1开始计数器,当计数器小于n时,继续循环

public static int sumOfSquares(int n) {
    // here you can check if n is greater than 0

    int counter = 1;
    int sum = 0;
    while (counter < n) {
        // [ sum up the square of the counter ]
        counter++;
    }

    return n;
}
publicstaticintsumofsquares(intn){
//在这里,您可以检查n是否大于0
int计数器=1;
整数和=0;
while(计数器因为这是一个作业,我不会给你答案。你应该看一下你的时间(总和>n)条件,并考虑这是不是真的。你还应该考虑while循环中的哪些代码实际上导致了“所有正整数的平方和小于或等于n”的计算。