6.1(数学:五角数)一个五角数被定义为n(3n-1)/2,其中n = 1,2,…。所以,开始的几个数字就是1,5,12,22,…,编写具有下面所示方法头的方法,返回一个五角数: public static int getPentagonalNumber(int n) 例如,getPentagonNumber(1)返回1,getPentagonNumber(2)返回5。编写一个测试程序显示前100个五角数,每行显示10个。使用%7d格式限定符来显示每个数字。 6.1(Math: pentagonal numbers) A pentagonal number is defined as n(3n-1)/2 for n = 1 , 2 , …, and so on. Therefore, the first few numbers are 1, 5, 12, 22, . . . . Write a method with the following header that returns a pentagonal number: public static int getPentagonalNumber(int n) For example, getPentagonalNumber(1) returns 1 and getPentagonalNumber(2) returns 5. Write a test program that uses this method to display the first 100 pentagonal numbers with 10 numbers on each line. Use the %7d format to display each number.
参考代码:
package chapter06;publicclassCode_01{publicstaticvoidmain(String[] args){int count =0;for(int i =1;i <=100;i++){
System.out.printf("%7d",getPentagonalNumber(i));
count++;if(count %10==0)
System.out.println();}}publicstaticintgetPentagonalNumber(int n){return n *(3* n -1)/2;}}
结果显示:
151222355170921171451762102472873303764254775325906517157828529251001108011621247133514261520161717171820192620352147226223802501262527522882301531513290343235773725387640304187434745104676484550175192537055515735592261126305650167006902710773157526774079578177840086268855908793229560980110045102921054210795110511131011572118371210512376126501292713207134901377614065143571465214950
Process finished with exit code 0