簡體   English   中英

用java編寫一個程序來打印從50到250(包括50和250)的所有3的倍數且不能被9整除的數字之和

[英]Write a program in java to print the sum of all numbers from 50 to 250(inclusive of 50 and 250) that are multiples of 3 and not divisible by 9

/* 當我運行這段代碼時沒有錯誤,實際上生成的輸出也是正確的,但我想知道這段代碼中的邏輯錯誤是什么? 請任何人解釋什么是邏輯錯誤。 */

class abc
    {
        public static void main(String arg[]){
        int sum=0;
        //for-loop for numbers 50-250
        for(int i=50;i<251;i++){
            // condition to check if number should be divided by 3 and not divided by 9 
            if(i%3==0 & i%9!=0){
                //individual number which are selected in loop
                System.out.println(i);
                //adding values of array so that total sum can be calculated
                sum=sum+i;   
            }   
        }
        //final display output for the code 
        System.out.println("the sum of intergers from 50 to 250 that are multiples of 3 and not divisible by 9 \n"+sum);
    }
}

我的理念是“更少的代碼 == 更少的錯誤”:

int sum = IntStream.rangeClosed(50, 250)
    .filter(i -> i % 3 == 0)
    .filter(i -> i % 9 != 0)
    .sum();

一條線。 易於閱讀和理解。 沒有錯誤。

改變這個:

if(i%3==0 & i%9!=0){

對此:

if(i%3==0 && i%9!=0){

& = 按位和運算符

&& = 邏輯運算符

Java中&和&&的區別?

我看到的唯一問題是:

  • 變量sum未聲明
  • 使用&&代替&

int sum = 0;
for (int i = 50; i <= 250; i++) {
    if (i % 3 == 0 && i % 9 != 0) {
        System.out.println(i);
        sum = sum + i;
    }
}
System.out.println("the sum of intergers from 50 to 250 that are multiples of 3 and not divisible by 9 \n" + sum);

好吧,與其像在這里for(int i=50;i<251;i++)那樣觸及從 50 到 250 的每一個值,你可以考慮這樣的事情......

int i = 48;
int sum = 0;
while(i < 250) {
    i += 3;
    if(i%9 != 0)
        sum += i;
}

這在某種意義上進行了優化,因為我跳過了我知道不可能的值。

但是,您的代碼中有一個更大的問題。 下面的代碼塊打印true ,當然。 但是,依賴&是一個壞主意,因為這不是它的工作。 &用於按位與,而&&用於邏輯與,這就是您想要做的。

boolean t = true;
boolean f = false;
System.out.println(f&t);

為什么?

在 Java 中,如果是&&操作,只要找到第一個false ,就可以確定表達式的計算結果為 false。 同時,在您的實施中,需要評估雙方。 f&t將評估為 false,但 JVM 需要查看ft變量。 同時,在使用&& ,它甚至不需要查看t

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM