猜数游戏:
public class Au { public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); int number = (int)(Math.random()*100+1); int a; int count = 0; do{ a = in.nextInt(); count = count +1; if(a<number){ System.out.println("偏小了"); } else if(a>number){ System.out.println("偏大了"); } }while(a != number); System.out.println("恭喜你,猜对了,你猜了"+count+"次"); } }
逆序:
public class Au { public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); int number = in.nextInt(); do { int digit = number % 10; System.out.print(digit); number = number / 10; } while (number > 0); } }
输出结果:
700
007
改进:
public class Au { public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); int number = in.nextInt(); int result = 0; do { int digit = number % 10; result = result*10 +digit; number = number / 10; } while (number > 0); System.out.println(result); } }
输出结果:
700
7
写出计算f=1+1/2+1/3+……+1/n的程序:
public class Au { public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); int n = in.nextInt(); double sum = 0.0; for(int i=1; i<=n; i++){ sum += 1.0/i; } System.out.println(sum); } }
输出结果:
100
5.187377517639621
如果想要输出的结果保留两位小数呢?就要对输出的格式进行变化,在System.out.print上做改动:
public class Au { public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); int n = in.nextInt(); double sum = 0.0; for(int i=1; i<=n; i++){ sum += 1.0/i; } System.out.printf("%.2f",sum); } }
输出结果:
100
5.19
如果要求f=1-1/2+1/3-1/4+……+1/n呢?对上面的程序再做改进,引入sign:
public class Au { public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); int n = in.nextInt(); double sum = 0.0; int sign = 1; for(int i=1; i<=n; i++){ sum += sign * 1.0/i; sign = -sign; } System.out.printf("%.2f",sum); } }
或者,也可以下面这种方法:
public class Au { public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); int n = in.nextInt(); double sum = 0.0; int sign = 1; for(int i=1; i<=n; i++){ // sum += sign * 1.0/i; // sign = -sign; if( i%2 == 1 ){ sum += 1.0/i; } else{ sum -= 1.0/i; } } System.out.printf("%.2f",sum); } }
求两个数的最大公约数:
public class Au { public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); int a = in.nextInt(); int b = in.nextInt(); int gcd = 1; for(int i=2; i<=a && i<=b; i++){ if(a%i==0 && b%i==0){ gcd=i; } } System.out.println(a+"和"+b+"的最大公约数是"+gcd); } }
辗转相除法:
public class Au { public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); int a = in.nextInt(); int b = in.nextInt(); while(b!=0){ int r = a % b; a = b; b = r; } int gcd = a; System.out.println(gcd); } }
时间: 2024-10-01 04:31:41