1.三角形
for(int m = 1; m <= 10; m++) { for (int n = 1; n <= m; n++) { System.out.print("*"); } System.out.println(); }
for(int m = 1; m <= 9; m++) { for (int n = 9; n >= m; n--) { System.out.print("*"); } System.out.println(); } 或 for(int m = 9; m >= 1; m--) { for (int n = 1; n <= m; n++) { System.out.print("*"); } System.out.println(); }
for (int m = 1; m <= 10; m++) { //输出空格 for (int n = 9; n >= m ;n--) { System.out.print(" "); } //输出* 左上 for (int n = 1; n <= m; n++) { System.out.print("*"); } System.out.println(); }
for (int m = 1; m <= 10; m++) { //输出空格 for (int n = 9; n >= m ;n--) { System.out.print(" "); } //输出* for (int n = 1; n <= m; n++) { System.out.print("*"); } System.out.println(); } for (int m = 1; m <= 9; m++) { //输出空格 for (int n = 1; n <= m ;n++) { System.out.print(" "); } //输出* for (int n = 9; n >= m; n--) { System.out.print("*"); } System.out.println(); }
for (int m = 1; m <= 10; m++) { //输出空格 for (int n = 9; n >= m ;n--) { System.out.print(" "); } //输出* 左上 for (int n = 1; n <= m; n++) { System.out.print("*"); } //右上 for (int n = 1; n <m; n++) { System.out.print("*"); } System.out.println(); }
2.菱形
//上半部分 for (int m = 1; m <= 10; m++) { //输出空格 for (int n = 9; n >= m ;n--) { System.out.print(" "); } //输出* 左上 for (int n = 1; n <= m; n++) { System.out.print("*"); } //右上 for (int n = 1; n <m; n++) { System.out.print("*"); } System.out.println(); } //下半部分 for (int m = 1; m <= 9; m++) { //输出空格 for (int n = 1; n <= m ;n++) { System.out.print(" "); } //输出* 左下 for (int n = 9; n >= m; n--) { System.out.print("*"); } //右下 for (int n = 9; n > m; n--) { System.out.print("*"); } System.out.println(); }
3.穷举
(1)一猴子一天吃一半,再扔一个,...到第7天发现只剩1个桃子,那么第一天有多少个桃子?
int sum=1; for(int i=6;i>=1;i--) { sum=(sum+1)*2; } System.out.println("桃子的总个数sum="+sum);
(2)国际象棋,第一格放一袋粮食,第二个放的是第一格的2倍,....以此类推,最后一格放多少(国际象棋共64个格)?
double sum = 1; for(int i=1;i<=64;i++) { sum*=2; } System.out.println("最后一个放的粮食数sum="+sum);
(3)添加符号“+”或“-”,使得123()45()67()8()9=100。
for(int a=-1;a<=1;a+=2) { for(int b=-1;b<=1;b+=2) { for(int c=-1;c<=1;c+=2) { for(int d=-1;d<=1;d+=2) { if(123+a*45+b*67+c*8+d*9==100) { System.out.println("运算式是:123+("+a+")x45+("+b+")x67(+"+c+")x8+("+d+")x9=100"); } } } } }