0

我的老师想要从 x 到 y 的所有数字的总和……比如 x+(x+1)+(x+2)……直到 y。但我认为我在这里做错了什么!

有人可以告诉我这里有什么问题吗?

#include <stdio.h>

int sum_naturals(int n)
{
  return (n-1) * n / 2;
}

int sum_from_to(int m)
{
  return (m-1) * m / 2;
}

void test_sum_naturals(void)
{
  int x;
  scanf("%d", &x);
  int z = sum_naturals(x);
  printf("%d\n", z);
}

void test_sum_from_to(void)
{
   int x;
   int y;
   scanf("%d", &x);
   scanf("%d", &y);
   int z = sum_naturals(x);
   int b = sum_from_to(y);
   printf("%d\n", z);
}

 int main(void)
{
 //test_sum_naturals();
  test_sum_from_to();
  return 0;
}
4

2 回答 2

1

Here's one solution :

#include<stdio.h>

int sum_naturals(int n)
{
  return (n+1) * n / 2;
}

int sum_from_x_to_y(int x, int y){
    return sum_naturals(y) - sum_naturals(x);
}

main()
{
     printf ("Sum: %d \n",sum_from_x_to_y(5, 10));
     printf ("Sum: %d \n",sum_from_x_to_y(0, 10));
     printf ("Sum: %d \n",sum_from_x_to_y(0, 5));
    return 0;
}

Note : sum from 0 to N is (n+1)*n/2 and not (n-1)*n/2

于 2014-09-23T11:12:18.197 回答
1

Your code should in fact be:

int sum_naturals(int n)
{
    return (n+1) * n / 2;
}

int sum_from_to(int m)
{
    return (m+1) * m / 2;
}

Notice + instead of your -.

To find the sum just add in the function test_sum_from_to this line:

printf("The sum is %d", b-z);
于 2014-09-23T11:14:17.987 回答