Odd Sum
Given a range [a,b], you are to find the summation of all the odd integers in this range. For example, the summation of all the odd integers in the range [3,9] is 3 + 5 + 7 + 9 = 24.
Input
There can be at multiple test cases. The first line of input gives you the number of test cases,T (1≤ T≤ 100)
Then T test cases follow. Each test case consists of 2 integers a and b (0≤ a≤ b≤ 100 )in two separate lines.
Output
For each test case you are to print one line of output - the serial number
of the test case followed by the summation of the odd integers in the range
[a, b].
Sample Input
2
1
5
3
5
Sample Output
Case 1: 9
Case 2: 8
Notes:
1.儲存輸入的資料
total:表示資料有幾筆,也就是有多少個test case
pairs陣列:存放每一筆輸入的起點a與終點b
int total;
scanf("%d", &total);
int input=2*total;
int pairs[input];
int i=1,start,end,k,sum;
while(i<=input){
scanf("%d",&pairs[i]);
i++;
}
Code:
#include <stdio.h>
int main(void){
int total;
scanf("%d", &total);
int input=2*total;
int pairs[input];
int i=1,start,end,k,sum;
while(i<=input){
scanf("%d",&pairs[i]);
i++;
}
for(i=1;i<=input;i+=2){
sum=0;
(pairs[i]%2)?start=pairs[i]:start=pairs[i]+1;
(pairs[i+1]%2)?end=pairs[i+1]:end=pairs[i+1]-1;
for(k=start;k<=end;k+=2)
sum+=k;
printf("Case %d: %d\n",(i/2+1),sum);
}
return 0;
}
沒有留言:
張貼留言