C語言:試寫一C程式,以迴圈計算...的值

試寫一C程式,以迴圈計算 12 − 22 + 32 − 42 + … + 472 − 482 + 492 − 502 的值

程式執行結果----------------------------------------------1^2 − 2^2 + 3^2 − 4^2 + ... + 49^2 − 50^2 = −1275Press any key to continue

3 Answers

Rating
  • 1 decade ago
    Favorite Answer

    #include int main( void )

    {

    int sum = 0;

    int i = 0;

    for(i = 1 ; i <= 50 ; i++)

    {

    if(i % 2 == 0)/*偶數的平方要減掉*/

    sum -= i*i;

    else

    sum += i*i;

    }

    printf("1^2 - 2^2 + 3^2 - 4^2 + ... + 49^2 - 50^2 = %d\n" , sum);

    printf("Press any key to continue\n");

    scanf(" ");

    return 0;

    }

    2011-01-07 01:45:58 補充:

    #include的後面應該要用一個

    < >

    來包住stdio.h

    2011-01-10 00:02:11 補充:

    哇好厲害

    原來可以這樣

    大師快去回答XD

    謝謝你唷我會學起來

    Source(s): , 自己
  • 1 decade ago

    數學解,永遠是其它任何單一解法達不到的!

    沒有數學,就沒有好的程式!

    切記!

  • 1 decade ago

    1^2-2^2+3^2-4^2+...+(2n-1)^2 - (2n)^2 =

    (1-2)*(1+2) + (3-4)*(3+4) + ... + (-1)*(2n-1+2n) =

    (-1)* (1+2+3+4+ ... + 2n-1 + 2n) =

    (-1)* (1+2n)*2n/2 =

    (-1)* n * (2n+1)

    in your case, where n=25

    -1 * 25 * (2*25+1) = -1275

    N=25;

    for(i=sum=0; i <= 2*N; ++i) sum -= i;

    printf("%d\\n", sum);

Still have questions? Get your answers by asking now.