在C中练习以计算从x到y的和

时间:2014-09-23 10:56:54

标签: c imperative-programming

我的老师想要从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;
}

2 个答案:

答案 0 :(得分:1)

这是一个解决方案:

#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;
}

注意:0到N之和为(n + 1)* n / 2且(n-1)* n / 2

答案 1 :(得分:1)

您的代码实际上应该是:

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

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

请注意+而不是-

要查找总和,只需在函数test_sum_from_to中添加此行:

printf("The sum is %d", b-z);