[英]Sum in C, from two numbers
Im creating a simple program in C that user insert a number, for example 5 and the program sums until 5, 0+1+2+3+4. 我在C中创建一个简单的程序,用户插入一个数字,例如5,程序总和直到5,0 + 1 + 2 + 3 + 4。 Im using this formula
我正在使用这个公式
int sum_naturals(int n){
return (n-1)*n/2;
}
But now i want a formula that can sum from 2 different numbers, like user inserts number 5 and 9 and the program will do 5+6+7+8+9. 但现在我想要一个可以从2个不同数字求和的公式,例如用户插入数字5和9,程序将执行5 + 6 + 7 + 8 + 9。
Can someone have ideia how can resolve this? 有人可以有ideia如何解决这个问题? Thanks
谢谢
You can reuse your function 您可以重复使用您的功能
int sum(int a, int b) {
return sum_naturals(b) - sum_naturals(a-1)
}
Of course you have to add some validation. 当然你必须添加一些验证。
Why not this? 为什么不呢?
int sum_2_naturals(int n, int m){
return (sum_naturals(m) - sum_naturals(n))
}
But now i want a formula that can sum from 2 different numbers,
但是现在我想要一个可以从2个不同数字求和的公式,
To find the sum of a certain number of terms of an arithmetic sequence: 要查找算术序列的一定数量项的总和:
#include <stdio.h>
static int sum_naturals(int a, int b)
{
return ((b - a + 1) * (a + b)) / 2;
}
int main(void)
{
printf("%d\n", sum_naturals(5, 9));
return 0;
}
Output: 输出:
35
Looks like a simple task, but since you still have problems understanding it, why don't you 'define' your functions first - before 'coding' them. 看起来像一个简单的任务,但由于你仍然无法理解它,为什么不先'定义'你的函数 - 在'编码'它们之前。
S ( n ) = 0 + 1 + 2 + ... + n -1 = n ( n -1)/2 S ( n )= 0 + 1 + 2 + ... + n -1 = n ( n -1)/ 2
F ( k , n ) = k + k +1 + ... + n -1 + n = -(0 + 1 + ... + k -1) + (0 + 1 + ... + k -1) + k + k +1 + ... + n -1 + n = - S ( k ) + S ( n ) + n = S ( n +1) - S ( k ) F ( k , n )= k + k +1 + ... + n -1 + n = - (0 + 1 + ... + k -1)+(0 + 1 + ... + k -1 )+ k + k +1 + ... + n -1 + n = - S ( k )+ S ( n )+ n = S ( n +1) - S ( k )
Of course, need to assume that k <= n etc. 当然,需要假设k <= n等。
I guess the reason of all confusion is that you defined your basic function to sum from 0 to n -1, instead of 1 to n . 我想所有混淆的原因是你定义了你的基本函数,从0到n -1,而不是1到n之和 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.