第六題:輸入兩個正整數m和n,求其最大公約數和最小公倍數。
package test11;
import java.util.Scanner;
public class Test6 {
/**
* 題目:輸入兩個正整數m和n,求其最大公約數和最小公倍數。 在循環中,只要除數不等於0,用較大數除以較小的數,將小的一個數作爲下一輪循環的大數,
* 取得的餘數作爲下一輪循環的較小的數,如此循環直到較小的數的值爲0,返 回較大的數,此數即爲最大公約數,最小公倍數爲兩數之積除以最大公約數。
*/
public static void main(String[] args) {
System.out.println("輸入一個整數:");
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
System.out.println("請再輸入一個整數:");
int b = sc.nextInt();
deff de = new deff();
int m=de.deff(a, b);
int n=a*b/m;
System.out.println(a+"和"+b+"的最小公倍數是:"+n+"。最大公約數是:"+m);
}
static class deff {
public int deff(int x, int y) {
int num;
if (x < y) {
num = x;
x = y;
y = num;
}
while (y != 0) {
if (x == y) {
return x;
} else {
int k = x % y;
x = y;
y = k;
}
}
return x;
}
}
}
運行結果:
第七題:輸入一行字符,分別統計出其中英文字母、空格、數字和其它字符的個數。
package test11;
import java.util.Scanner;
public class Test7 {
public static void main(String[] args) {
int digital = 0;
int character = 0;
int other = 0;
int blank = 0;
System.out.println("請輸入內容:");
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
char[] cs = s.toCharArray();
for (int i = 0; i < cs.length; i++) {
if (cs[i]>='0'&&cs[i]<='9') {
digital++;
}else if (cs[i]>='a'&&cs[i]<='z') {
character++;
}else if (cs[i]==' ') {
blank++;
}else {
other++;
}
}
System.out.println("這串字符串共有數字"+digital+"個,字母"+
character+"個,空格"+blank+"個,其他字符"+other+"個。");
}
}
運行結果:
第八題:求s=a+aa+aaa+aaaa+aa...a的值,其中a是一個數字。例如2+22+222+2222+22222(此時共有5個數相加),幾個數相加有鍵盤控制。
package test11;
import java.util.Scanner;
public class Test8 {
/*
* 題目:求s=a+aa+aaa+aaaa+aa...a的值,其中a是一個數字。
* 例如2+22+222+2222+22222(此時共有5個數相加),幾個數相加有鍵盤控制。
**/
public static void main(String[] args) {
Scanner scanner =new Scanner(System.in);
int sum = 0;
int sum1 = 0;
System.out.println("請輸入一個數字:");
int n = scanner.nextInt();
System.out.println("請輸入他要加多少次:");
int m = scanner.nextInt();
int i =1;
while (i<=m) {
int j=0;
j+=n;
sum+=j;
sum1+=sum;
n*=10;
++i;
}
System.out.println(sum1);
}
}
運行結果:
第九題:一個數如果恰好等於它的因子之和,這個數就稱爲 "完數 "。例如6=1+2+3.編程 找出1000以內的所有完數。
package test11;
public class Test9 {
public static void main(String[] args) {
for (int i = 1; i <= 1000; i++) {
int t = 0;
for (int j = 1; j <= i/2; j++) {
if (i%j==0) {
t+=j;
}
}
if (t==i) {
System.out.println(" "+i);
}
}
}
}
運行結果:
第十題:一球從100米高度自由落下,每次落地後反跳回原高度的一半;再落下,求它在 第10次落地時,共經過多少米?第10次反彈多高?
package test11;
public class Test10 {
public static void main(String[] args) {
int s =100;
int h = 100;
for (int i = 0; i < 10; i++) {
s+=h;
h=h/2;
}
System.out.println("路程爲"+s+"高度爲"+h);
}
}
運行結果: