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