1.while循环求所有的三位水仙花数。
ps:三位数是从100-999
public class Flower{
public static void main(String arge[]){
int n = 100;
while (n < 1000) {
int a = n / 100 % 10;//int a=n/100;
int b=(n-a*100)/10;//int b = n / 10%10;
int c = n % 10;
if (Math.pow(a, 3) + Math.pow(b, 3) + Math.pow(c, 3) == n) {
System.out.println("水仙花数"+n);
}
n++;
}
}
}
- 从键盘输入一个长整数,求其各位数字之和。
import javax.swing.JOptionPane;
public class LongInt {
public static void main(String arge[]){
long m=0;
Long n=Long.parseLong(JOptionPane.showInputDialog("请输入一个长整数:"));
while(n>0) {
m+=n%10;//m=m+n%10
n=n/10;
}
System.out.print(m);
}
}
- 计算1+1/2+1/3+…+1/100的和
public class Sum1 {
public static void main(String args[]){
double sum=1; //计算变量包含小数,要使用double类型
for(int i=2;i<=100;i++) {
sum+=1.0/i; //1.0写成1会变成整除运算
}
System.out.print(sum);
}
}
5.187377517639621
- 斐波那契数列,列出Fibonacci数列的前10个数。(包括第10个)
public class Fibonacci {
public static void main(String arge[]){
int a=0,b=1;
System.out.print(a+" "+b+" ");
for(int i=3;i<=10;i++) {
int c=a+b;
a=b;
b=c;
System.out.print(c+" ");
}
}
}
- 利用随机函数产生3道两位数加法测试题,根据用户的解答计入得分。(答对加一分,答错不加分)
import javax.swing.JOptionPane;
public class Caculate {
public static void main(String arge[]){
int grade=0;
for(int i=1;i<=3;i++) {
int x=10+(int)(Math.random()*90);
int y=10+(int)(Math.random()*90);
int s=Integer.parseInt(JOptionPane.showInputDialog("请计算"+x+"+"+y+"="));
System.out.println(x+"+"+y+"="+s);
if(s==x+y) {
grade+=1;
}
}
System.out.print("你的得分是:"+grade);
}
}
- 嵌套循环,求3~50内的素数并一行输出5个。
ps:素数是只能被1和它本身整除的数。
public class Prime {
public static void main(String args[]) {
int m=0;
for(int i=3;i<=50;i++) {
boolean f=true;
int k=2;
while(f&&k<i) {
if(i%k==0) {
f=false;
}
k++;
}
if(f) {
System.out.print(i+"\t");
m++;
if(m%5==0) {
System.out.println();
}
}
}
}
}