【问题标题】:find and display the sum of the cubes of the first n natural numbers查找并显示前 n 个自然数的立方和
【发布时间】:2015-04-21 19:38:36
【问题描述】:

我需要找到并显示前 n 个自然数的立方和,而我目前使用的代码似乎只能打印到我想要​​的范围。

最大是 20,它打印我的数字的立方体最多 20。我为求和编写的循环不起作用,通常会使程序崩溃。

任何有关如何制作它的帮助或想法,以便程序只对输入的数字进行立方,然后将这些立方相加,我们将不胜感激,请保持简单。

public class MyIntNumberr
{ // construct a myintnumber with one instance field n
    public MyIntNumberr(int n)
    {
        number = n;
    }

    public void calcCubeAndSum(int num)
    {

        if (num < 0)
        {
            System.out.println("that integer is invalid please try again");
            System.exit(0);
        }
        while (num >= 1 && num <= 20)
        {
            System.out.println(" " + num + "      " + Math.pow(num, 3));
            num = num + 1;
        }

    }

    // instance fields
    private int number;
}


import javax.swing.JOptionPane;

public class MyIntNumberTestt
{
    public static void main(String[] args)
    {
        int number, num;

        String input = JOptionPane.showInputDialog("enter a value to cube and gather  the sum of");
        num = Integer.parseInt(input);

        MyIntNumberr richard = new MyIntNumberr(num);

        richard.calcCubeAndSum(num);

        System.exit(0);
    }
}

【问题讨论】:

    标签: loops for-loop while-loop


    【解决方案1】:

    我没有在您的代码中看到您累积立方体总和的位置...

    static Scanner input = new Scanner(System.in);
    
    public static void main(String[] args) throws Exception {    
        System.out.print("Enter a value to cube and gather the sum of: ");
        int num = input.nextInt();
        calcCubeAndSum(num);
    }
    
    private static void calcCubeAndSum(int num) {
        if (1 <= num && num <= 20) {
            int sum = 0;
            while (num <= 20) {
                // Calculate the cube
                int cube = num * num * num;
    
                // Accumulate the cube into a sum
                sum += cube;
    
                // Display current result
                System.out.println("Current number: " + num + "\tCubed: " + cube + "\tCurrent Sum: " + sum);
    
                // Go to the next number
                num++;
            }
            // Display Total Sum
            System.out.println("Total Sum: " + sum);
        } else {
            System.out.println("That integer is invalid please try again");
        }
    }
    

    结果:

    【讨论】:

      【解决方案2】:

      这是使用 Python 查找 N 个自然数的简单方法 希望大家喜欢....

      n = int(input("Enter the value of n:"))
      for i in range (1,n+1):
          print(i)
      

      回答

      Enter the value of n:10
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      

      【讨论】:

      • 我不确定原始帖子是否在寻找 python 答案。
      猜你喜欢
      • 1970-01-01
      • 2020-12-28
      • 2020-02-03
      • 1970-01-01
      • 1970-01-01
      • 2020-12-12
      • 2015-12-06
      • 2013-10-22
      • 2019-06-20
      相关资源
      最近更新 更多