1.使用while循环语句计算1+1/2!+1/3!+…+1/20!
package hello;
public class Hello {
public static void main(String[] args) {
int num = 2;
int i_sum = 1;
float j = 1.0f;
float sum = 1.0f;
while(num < 21){
for(int i = 1;i <= num;i++){
i_sum = i_sum * i;
}
sum = sum + (j / i_sum);
i_sum = 1;
num++;
}
System.out.println(sum);
}
}
2.用java写程序,输出一个实心菱形
package hello;
public class Hello {
public static void main(String[] args) {
//打印上半部分
for(int row = 1;row <= 5;row++){
for(int i = 1;i <= ( 5 - row );i++){
System.out.print(" "); //打印空格
}
for(int j = 1;j <= (row * 2 - 1);j++){
if(row == 1){
System.out.print("*");
break;
}
System.out.print("*"); //打印*号
}
System.out.println();
}
//打印下半部分
for(int row = 1;row <= 4;row++){
for(int i = 1;i <= row;i++){
System.out.print(" "); //打印空格
}
for(int j = 1;j <= 7 - (row - 1) * 2 ;j++){
System.out.print("*"); //打印*号
}
System.out.println();
}
}
}
//以下是输出结果
3.用java程序输出空心菱形
package hello;
public class Hello {
public static void main(String[] args) {
//打印上半部分
for(int row = 1;row <= 5;row++){
if(row == 1){
for(int i = 1;i <= 4;i++){
System.out.print(" ");
}
System.out.print("*");
}
else{
for(int j = 1;j <= 5 - row;j++){
System.out.print(" "); //打印空格
}
System.out.print("*");
for(int k = 1;k <= (row -1) * 2 - 1;k++){
System.out.print(" ");
}
System.out.print("*");
}
System.out.println();
}
//打印下半部分
for(int row = 1;row <= 4;row++){
if(row == 4){
for(int i = 1;i <= row;i++){
System.out.print(" "); //打印空格
}
System.out.print("*");
}
else{
for(int j = 1;j <= row;j++){
System.out.print(" "); //打印空格
}
System.out.print("*");
for(int k = 1;k <= 5 - (row -1) * 2;k++){
System.out.print(" "); //打印空格
}
System.out.print("*");
}
System.out.println();
}
}
}
//以下是输出结果