promotion image of download ymail app
Promoted

誰會用SUM迴圈寫JAVA程式1~100總和

我要1~100之總和,還有0~80之偶數總和,0~50之單數總和,分開顯示,只能用 SUM寫兩個迴圈來表示歐

3 Answers

Rating
  • 1 decade ago
    Favorite Answer

    public class Sum {

    public static void main(String arg[]) {

    int odd = 0;//單數總合

    int even = 0;//雙數總和

    int total = 0;//全部總和

    int sum = 0;//用sum接所有總和

    // 1~100總和

    int a = 1, b = 100;

    total = ((a+b) * 100) / 2;

    sum = total;

    System.out.println( 〝1~100總和〞+ sum);

    // 0~80之偶數

    for (int i = 0; i <=80; i = 2) {

    even += i;

    sum = even;

    }

    System.out.println(〝0~80偶數之總和〞+ sum);

    // 0~50之奇數

    for (int i = 1; i <=50; i = 2) {

    odd += i;

    sum = odd;

    }

    System.out.println(〝0~50之奇數總和〞+ sum);

    }

    }

    Source(s): 小弟剛接觸JAVA來此練功~給您參考唷~
    • Commenter avatarLogin to reply the answers
  • 1 decade ago

    public class Adder {

    public static void main(String args []){

    int sum= 0 ; // 1~100之總和

    int oddSum = 0 ; // 0~50 之單數總和

    int evenSum = 0 ; // 0~80 之偶數總和

    for (int i = 1 ; i <= 100 ; i++){

    sum += i ;

    //判別0~80內的單數並加總至 evenSum

    if(i <= 80 && i % 2 == 0 ){

    evenSum += i ;

    }

    //判別0~50內的偶數並加總至 oddSum

    if(i <= 50 && i % 2 == 1 ){

    oddSum += i ;

    }

    }

    System.out.println("1~100總和為:"+sum);

    System.out.println("0~80偶數總和為:"+evenSum);

    System.out.println("0~50單數總和為:"+oddSum);

    }

    }

    -------------------------------分隔線------------------------------------

    備註:請將全形的 "改為半形的 " 改完後再貼入程式才可執行!!

    有點看不懂你所謂:"只能用SUM寫兩個迴圈來表示"

    不過上述程式碼只用了一個for迴圈

    Source(s): 自己
    • Commenter avatarLogin to reply the answers
  • 1 decade ago

    只能用 SUM寫兩個迴圈來表示歐 是什麼意思呀

    不過我寫的話會是這樣

    public class Sum {

    int oddSum = 0;

    int evenSum = 0;

    int totalSum = 0;

    public Sum() {

    for (int i=1; i<100; i++) {

    totalSum = totalSum + i;

    if (i%2==0 && i <= 80) {

    evenSum = evenSum + i;

    } else if (i%2==i && i < 50){

    oddSum = oddSum + i;

    }

    }

    System.out.println("1~100之總和是: " + totalSum);

    System.out.println("0~80之偶數總和: " + evenSum);

    System.out.println("0~50之單數總和: " + oddSum);

    }

    public static void main(String args[]) {

    Sum app = new Sum();

    }

    }

    Source(s): 自己
    • Commenter avatarLogin to reply the answers
Still have questions? Get your answers by asking now.