java-循环结构

1、求一个整数,在内存当中存储时,二进制1的个数。

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int count=0;
        while(a!=0){
            count++;
            a=a&(a-1);
        }
        System.out.println(count);
    }
}

2、求两个正整数的最大公约数

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();
        int temp;
        temp=a>b? b:a;
        for(int i=temp;i>0;i--){
            if(a%i==0&&b%i==0){
                System.out.println(i);
                break;
            }
        }
    }
}

3、计算1/1-1/2+1/3-1/4+1/5 …… + 1/99 - 1/100 的值 。

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        double a=1;
        double sum_1=0;
        int flag=1;
        for(double b=1;b<=100;b++) {
         sum_1=sum_1+flag*(a/b);
         flag=-flag;
        }
        System.out.println(sum_1);
    }
}

4、求出0~999之间的所有“水仙花数”并输出。(“水仙花数”是指一个三位数,其各位数字的立方和确好等于该数本 身,如;153=1+5+3?,则153是一个“水仙花数“。)

mport java.util.Scanner;
import java.math.*;

public class Main {
    public static void main(String[] args) {
        double a = 0;
        double b = 0;
        double c = 0;
        for (int i = 100; i < 1000; i++) {
            a = Math.pow(i % 10, 3);
            b = Math.pow(i / 10 % 10, 3);
            c = Math.pow(i / 100, 3);
            if (a + b + c == i) {
                System.out.println(i);
            }
        }
    }
}

5、完成猜数字游戏

import java.util.Random;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Random random = new Random();
        int goal = random.nextInt(101);
        System.out.print("请输入你猜的数字0-100:");
        Scanner sc = new Scanner(System.in);
        while(true) {
            int a = sc.nextInt();
            if (a < goal) {
                System.out.println("你猜小了");
            } else if (a == goal) {
                System.out.println("你猜对了");
                break;
            } else if (a > goal) {
                System.out.println("你猜大了");
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值