網頁

工商專區

2014年1月4日

求兩數奇數和

已知a、b兩正整數,b大於或等於a,求兩數間的奇數和

例:
a=2、b=6
out=8

a=3、b=6
out=8

a=7、b=7
out=7

a=4、b=4
out=0

  1. import java.util.Scanner;
  2.  
  3. public class Demo {
  4.  
  5. public static void main(String[] args) {
  6.  
  7. Scanner sc = new Scanner(System.in);
  8. int a = sc.nextInt();
  9. int b = sc.nextInt();
  10.  
  11. if(a%2==0)
  12. {
  13. a++;
  14. }
  15.  
  16. if(b%2==0)
  17. {
  18. b--;
  19. }
  20.  
  21. int n = (b-a)/2+1;
  22. System.out.println((a+b)*n/2);
  23.  
  24. }
  25. }







迴圈解法:
  1. import java.util.Scanner;
  2.  
  3. public class Demo {
  4.  
  5. public static void main(String[] args) {
  6.  
  7. Scanner sc = new Scanner(System.in);
  8. int a = sc.nextInt();
  9. int b = sc.nextInt();
  10.  
  11. if (a % 2 == 0) {
  12. a++;
  13. }
  14.  
  15. if (b % 2 == 0) {
  16. b--;
  17. }
  18.  
  19. int total=0;
  20. for (int i = a; i <= b; i += 2) {
  21. total +=i;
  22. }
  23.  
  24. System.out.println(total);
  25. }
  26. }

沒有留言:

張貼留言