【问题标题】:Understanding selections and looping in a divisor program了解除数程序中的选择和循环
【发布时间】:2019-10-10 01:16:04
【问题描述】:

我的作业是要求我使用定义的范围(通过输入范围中的最高数字)和用户输入的除数来查找范围内可被除数整除的所有数字,而不使用数学或赋值运算符++、- 或 = 除外(不允许使用 +、-、/、*、%、+=、%= 等)。

使用数学运算符编写该程序非常容易,但是当我尝试仅使用增量运算符编写它时,我每次都迷失了方向。我对编程非常陌生。

下面是我到目前为止的代码,但是它在除数之后打印范围(1到最大数字)中的每个数字(所以如果用户输入的除数是5并且最大数字是20,它将打印每个数字 5-20),而不仅仅是能被除数整除的数字 (5, 10, 15, 20)。

    input = new Scanner(System.in);

    // input the ending number
    System.out.println("Enter the ending number: ");
    n = input.nextInt();
    System.out.println("Enter the divisor: ");
    count = input.nextInt();
    variable = 0;
    System.out.println("Below are all the numbers that are evenly divisible by " + count + " from 1 up to " + n);

    while (count <= n){
        variable++; 
        if (variable == count){
            System.out.print(count + "  ");
            count++;}

【问题讨论】:

    标签: java loops if-statement increment


    【解决方案1】:

    循环计数多次, 现在下面应该可以工作了,最大奇数和偶数

     int temp = count;
        while(count<n)
        {
    
            for(int i=0; i<temp; i++)
            {
                 variable++;
    
            }
            if(variable>n) break;
            else {
            count = variable;
            System.out.println(count);
            }
    
        }
    

    【讨论】:

    • 这行得通,除了我需要将 count
    • 如果我投了反对票,我很抱歉,我以为我投了赞成票。这是我第一次使用这个网站。
    • @BrandonBischoff 没问题。
    猜你喜欢
    • 2012-06-19
    • 1970-01-01
    • 1970-01-01
    • 2018-09-19
    • 1970-01-01
    • 2018-06-16
    • 1970-01-01
    • 2013-05-30
    • 2014-03-15
    相关资源
    最近更新 更多