2016-10-07 5 views
0

내가 마음에 내 삼각형 번호 생성기, 곰 이상한 오류를 데 내가 프로그래밍에 아주 새로운 오전. 프로그램의 특정 지점 번호 결함 밖으로 일부가 마이너스 숫자에서 는 (이 숫자는 단지이없는 것을 주목할 필요가있다! - 그들 앞에서 실제로 밖으로 glitched된다)자바 삼각형 번호 계산기

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); 
      } 
     } 

    } 
+1

출력을 추가 할 수 있습니까? – Gaur93

+1

어떤 문제가 있습니까? –

+0

전체 비트 또는 홀수 비트에서의 출력? –

답변

0

온라인 삼각형 숫자를 보면 쉽게 = N (내가 위키 피 디아에서했던) 삼각형의 수 n에있는 모서리의 양이, (n)은 수학 타입 T에 의해 제공 될 수 있음을 발견 할 수 있습니다 (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 변수보다 최대 값을 제공하며 양 변수의 사용을 필요로하지 않습니다. 자바를 사용하는 동안

난 정말 그 상점 같은 자바를 사용하는 점을 그리워, u는 더 객체 지향 코드를 목표로한다.

0

보이는 것에서 보이는 문제는 Erwin Bolwidt정수 오버플로이라는 주석에서 응답되었습니다. 모든 것이 컴퓨터의 바이너리에 저장되기 때문에 특정 데이터 유형은 많은 양의 데이터 만 저장할 수 있습니다. 자바에서 int 프리미티브 우리 2147483647 또는 2^(31)-1의 최대 값을 제공하는 32 비트이다.

이것은 더 많은 데이터를 저장할 수 있기 때문에 메모리에 더 많은 리소스를 사용하지만 long 기본 데이터 형식을 사용하여 해결할 수 있습니다. long9223372036854775807 또는 2^(63)-1들의 최대 수를 제공하는 64 비트 데이터 타입이다.

출처 : Oracle Java Documentation

+0

감사! 정말 도움이되었습니다! –

+0

int를 오랫동안 변경하겠습니까? 지금은 이것을 얻었습니다. –

+0

스레드 "main"의 예외 java.util.InputMismatchException : 입력 문자열의 경우 : "10000000000" \t at java.util.Scanner.nextInt (Scanner.java:2123) \t at java.util.Scanner.nextInt (Scanner.java:2076) \t at TriangularNumbers.main (TriangularNumbers.java:11) –