无法确定while循环-输入n并返回小于或等于n的+整数的平方和 [英] Having trouble figuring out while loop - input n and return sum of squares of + integers less than or equal to n

查看:93
本文介绍了无法确定while循环-输入n并返回小于或等于n的+整数的平方和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我在循环时很难弄清楚这一点,我已经对其中的大部分进行了编码(非常像业余爱好者),但是我希望有人可以在我的逻辑和推理方面为我提供帮助.请在可能的情况下提供帮助!

Hello, I''m having trouble figuring this while loop out, I''ve coded most of it (very amateur-like) but I was hoping someone could help me with my logic and reasoning for this. Please help when possible thanks!

/*	Write a short Java method that takes an integer n and returns the sum of the
	squares of all positive integers less than or equal to n.
 * 
 */

public class ch1dot7 
{
	public static void main (String[]args)
	{
		Scanner input = new Scanner(System.in);
		
		int n, m = 0, sum = 0;
		
		System.out.print("Please enter a value for n: ");
		n = input.nextInt();
		
		System.out.println("n is currently: "+n);
		
		if (n <= 0)
		{
			System.out.print("Please enter a value that is higher than 0 (integer)");
			n = input.nextInt();
		}
		
		while  (sum > n)
		{
			
			System.out.print("Please enter a value for m (enter a value greater than n to exit): ");
			m = input.nextInt();
			
			if (m < n)
			{
				sum += m*m;
				System.out.println("sum of the squares is: " +sum);	
			}
			
			sum += m*m;
		}
		
	}//end main
	
	
}//end class

推荐答案

/*	Write a short Java method that takes an integer n and returns the sum of the
	squares of all positive integers less than or equal to n.
 * 
 */


考虑一下您的输入是什么,如何转换它们以及输出是什么.
1.仅需要一个输入,它是一个大于0的正整数(实际上可能大于1).
2.计算从N到1的所有整数的平方和.
3.打印该笔款项.

所以顺序是:


Think about what your inputs are, how they need to be transformed, and what the outputs are.
1. There is only one input required, which is a positive integer greater than 0 (probably greater than 1 in truth).
2. Calculate the sum of the squares of all integers from N to 1
3. Print that sum.

So the sequence is:

N = get a positive integer; // a small loop should do this
SUM = 0
WHILE N > 0
DO
    SQUARE = N * N
    SUM = SUM + SQUARE
    N = N - 1
END WHILE
PRINT "The total is: " + SUM


这篇关于无法确定while循环-输入n并返回小于或等于n的+整数的平方和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆