簡體   English   中英

給定范圍[a,b]中的奇數總和?

[英]Sum odd numbers from a given range[a,b]?

我正在通過UVA在線法官的一些練習進行練習,我嘗試做一個奇數和,基本上給定一個范圍[a,b],計算出從a到b的所有奇數之和。

我寫了代碼,但是由於某種原因,我不明白當范圍為[1,2]時會得到891896832,並且根據算法它應該為1,不是嗎?

import java.util.Scanner;
public class OddSum 
{
    static Scanner teclado = new Scanner(System.in);
    public static void main(String[] args)
    {
        int T = teclado.nextInt();
        int[] array = new int[T];
        for(int i = 0; i < array.length; i++) 
        {
            System.out.println("Case "+(i+1)+": "+sum());
        }
    }
    public static int sum()
    {
        int a=teclado.nextInt();
        int b = teclado.nextInt();
        int array[] = new int[1000000];
        for (int i = 0; i < array.length; i++) 
        {   
            if(a%2!=0)
            {               
                array[i]=a;
                if(array[i]==(b))
                {
                    break;
                }
            }   
            a++;    
        }
        int res=0;

        for (int i = 0; i < array.length; i++)
        {
            if(array[i]==1 && array[2]==0)
            {
                return 1;
            }

            else
            {
            res = res + array[i];
            }
        }
        return res;
    }
}

僅當間隔的上限為奇數時,才檢查停止條件。

移動

if (array[i] == (b)) {
    break;
}

if(a % 2 != 0)子句中。

通常,我認為您不需要數組,只需將循環中的奇數值相加即可,而不是將它們添加到數組中。

我現在沒有安裝Java,但是等效的C#如下:(在a和b中分配任何值)

        int a = 0;
        int b = 10;
        int result = 0;
        for (int counter = a; counter <= b; counter++)
        {
            if ((counter % 2) != 0) // is odd
            {
                result += counter;
            }
        }
        System.out.println("Sum: " + result);

沒有大戲,簡單n干凈。

通過簡單地沿途跟蹤總和,而不是將任何東西存儲在數組中,使它盡可能簡單。 如果索引為奇數,請使用for循環並將索引添加到總和中:

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Enter minimum range value: ");
    int min = keyboard.nextInt();
    System.out.println("Enter maximum range value: ");
    int max = keyboard.nextInt();
    int sum = 0;

    for(int i = min; i < max; i++) {
        if(i % 2 != 0) {
            sum += i;
        }
    }

    System.out.println("The sum of the odd numbers from " + min + " to " + max + " are " +  sum);
}

暫無
暫無

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

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