將a設為奇數比較好處理

Problem

-----------------------------------------------------------

#include <stdio.h>

int main()
{
    int _case, a, b, total, case_num = 1;

    scanf("%d", &_case);
    while(_case--)
    {
        scanf("%d%d", &a, &b);
        if( !(a%2) )
            a++;

        for(total = 0; a <= b; a += 2)
            total += a;

        printf("Case %d: %d\n", case_num++, total);
    }

    return 0;
}

 

----2017-06-24

import java.util.*;
public class main{
    public static void main(String[] args) {
        try {
            Scanner sc = new Scanner(System.in);
            int cases = sc.nextInt();

            for (int i = 1; i <= cases; i++) {
                int start = sc.nextInt(), end = sc.nextInt(), sum = 0;

                start = (start % 2) == 1 ? start : (start + 1);
                for (; start <= end; start += 2) {
                    sum += start;
                }
                System.out.println("Case " + i + ": " + sum);
            }
        } catch (Exception e) {
        }
    }
};
 

arrow
arrow
    全站熱搜

    awesq123 發表在 痞客邦 留言(0) 人氣()