Java三角数字计算器

时间:2016-10-07 04:56:36

标签: java

我的三角数字生成器出现奇怪错误,请记住我对编程很新。 在程序中的某个点上,数字会出现故障并且有些数字会变为负数(值得注意的是,这些数字不仅仅是 - 在它们面前它们实际上已经被搞定了!)

    import java.util.Scanner;

    public class TriangularNumbers {
       @SuppressWarnings("resource")
       public static void main(String args[]) {
            int tnumber = 1;
            int amount = 2;     
            System.out.println("Welcome to the triangular numbers         calculator!");
            System.out.println("Type in the amount of triangular numbers to be generated!");
            Scanner reps = new Scanner(System.in);
            int repeats = reps.nextInt();
            int i = 0;
            while (i < repeats) {
                i = i + 1;
                System.out.println(i + ". " + tnumber);
                tnumber = tnumber + amount;
                amount = (amount + 1);
            }
        }

    }

4 个答案:

答案 0 :(得分:0)

如果你在网上查找三角形数字,你可以很容易地发现(我在维基百科上做过)在三角数n中找到的角的数量,可以用数学类型T(n)= n(n + 1)2给出

因此计算它你可以做那样的事情(你的代码,微小的变化)

   public static void main(String args[]) {
        long tnumber;

        System.out.println("Welcome to the triangular numbers calculator!");
        System.out.println("Type in the amount of triangular numbers to be generated!");

        Scanner reps = new Scanner(System.in);
        int repeats = reps.nextInt();
        int i = 1;

        while (i <= repeats) {
            tnumber = i(i+1)/2;
            System.out.println(i + ". " + tnumber);
            i++;
        }
    }

此代码为您的tnumber变量提供更大的最大值,并且不需要使用金额变量。

我真的很想念使用Java这样的东西,你应该在使用java的同时针对更多面向对象的代码。

答案 1 :(得分:0)

您看到的问题,从它的外观来看,在Erwin Bolwidt的评论中被称为整数溢出。由于所有内容都存储在计算机上的Binary中,因此某些数据类型只能容纳如此多的数据。在Java中,int原语是32位,这使我们的最大值为21474836472^(31)-1

这可以使用long原始数据类型来解决,尽管它确实在内存中使用了更多资源(因为它可以存储更多数据)。 long是64位数据类型,其最大数量为92233720368547758072^(63)-1

来源:Oracle Java Documentation

答案 2 :(得分:0)

public static void main(String[] args){

    Scanner um=new Scanner(System.in);

    int y,x=0;
    System.out.print("Enter Number to find Triangular Number: ");
    int a=um.nextInt();
    for ( ; x < a; x++) {
        y= x*(x+1)/2;
        System.out.println("This is a Triangular Num: "+y);
    }   
}

答案 3 :(得分:0)

package domain;

public class HelloWorld {

  public static void main(String[] args) {
    int n =1;

    while(n<=45){
        System.out.println(n*3);
        n++;
    }
  }
}
相关问题