简单循环算法
1、使用嵌套循环输出1 2 3 4 5 6 7 8 9 …
/*
使用嵌套循环输出
1 2 3 4 5 6 7 8 9
2 4 6 8 10 12 14 16 18
3 6 9 12 15 18 21 24 27
4 8 12 16 20 24 28 32 36
5 10 15 20 25 30 35 40 45
6 12 18 24 30 36 42 48 54
7 14 21 28 35 42 49 56 63
8 16 24 32 40 48 56 64 72
9 18 27 36 45 54 63 72 81
*/
public class Test01 {
public static void main(String[] args) {
for (int i = 1; i <= 9 ; i++) {
//循环打印9行,相当于行号
int a=0; //每打印1行,a的值清零
for (int j = 0; j <9 ; j++) {
//每行打印的数字等于该行号依次累加,一共打印并累加行号9次
a+=i;
System.out.print(a+"\t");
}
System.out.println();
}
}
}
2、输入的正整数n,求n!,即n!=n*(n-1)(n-2)…*1
import java.util.Scanner;
/**
* 使用for循环实现:根据用户输入的正整数n,求n!,即n!=n*(n-1)*(n-2)*…*1。
*/
public class Test02 {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("请输入一个正整数:");
int n=input.nextInt();
int sum=1;
for (int i = n; i >=1 ; i--) {
//循环n次,每次循环sum*=i
if (i==1){
System.out.print(i);
}else {
System.out.print(i+"*");
}
sum*=i;
}
System.out.println("="+sum);
}
}
3、 百元钱买百只鸡问题
/**
* 百元钱买百只鸡问题)一只公鸡5元钱,一只母鸡3元钱,三只小鸡1元钱。要求100元买100只鸡,请给出所有可行的结果?
*/
public class Test03{
public static void main(String[] args){
for (int i = 0; i <=20 ; i++) {
int a=i*5;
for (int j = 0; j <=33 ; j++) {
int b=j*3;
for (int k = 0; k <=300; k+=3) {
int c=k/3;
if (i+j+k==100&&a+b+c==100){
System.out.println("公鸡"+i+"只需要"+a+"元"+",母鸡"+j+"只需要"+b+"元"+",小鸡"+k+"只需要"+c+"元");
}
}
}
}
}
}