我想要做的是获取从1开始的先前整数的累积和,例如: 如果我的输入为4,则该函数应以这种方式工作; 1 +(1 + 2)+(1 + 2 + 3)+(1 + 2 + 3 + 4)= 20。 输出必须为20。此外,我必须通过函数而不是main()来完成此操作。函数使用int n作为唯一变量。
我试图做的是一个将1与整数N相加的函数,并使用'for'使N从1开始,以便它可以将整数完全相加,直到达到N。
flutter create --org com appname
当输入为4时,我期望的是20,但实际输出为10。
答案 0 :(得分:1)
我会这样写,备注是进行更改的地方
#include <stdio.h>
int sum(int n);
int main() {
int n, input, sum;
// sum = 0; // no need for this
scanf("%d", &n);
/* the next for has no use
for (n = 0; n <= input; n++) {
sum += n;
} */
// I would be adding some input sanitazing if possible here
printf("%d", sum(n));
return 0;
}
int sum(int n) {
int i, /*n, */ rsum = 0; // n is already a parameter, rsum for running sum
// scanf("%d", &n); // nope nope, scanf and printf should be avoided in functions
for (i = 1; i <= n; i++){ // changed i +=1 with i++ , easier to read
for (j=1;j<=i;j++) // need this other loop inside
rsum += j;
}
return rsum;
}
答案 1 :(得分:0)
主要问题在于函数,您仅执行1个循环(您还有一些逻辑上的事情,编译器应告诉您,就像变量和函数的命名一样。)例如,
因此,如果您将放置
4 as the input
,则循环将仅执行1+2+3+4
,但是如果您的情况不同,则希望对所有迭代进行求和,例如1 + (1+2) + (1+2+3) + (1+2+3+4)
您基本上只在做最后一步(1 + 2 + 3 + 4),进行4次迭代(4x总和),但实际上您需要进行10次迭代(由于所有元素的特定总和而得总和)
根据建议,尝试调试代码-What is a debugger and how can it help me diagnose problems? -确实可以帮助您理解代码
如上所述,问题出在
int sum(int n) {
int i, n, sum = 0;
scanf("%d", &n);
for (i = 1; i <= n; i += 1){
sum += i;
}
return n;
}
您必须进行两个循环,例如。如下所示:
int sum,n = 0;
//scanf("%d", &n);
n = 4; //input simulation
//just for demonstration
int iterations = 0;
//counter for total loops (how many "brackets" needs to be count)
for(int loopsCounter = 1; loopsCounter <= n;loopsCounter++){
//counter for child elements in brackets (like 1+2 ,1+2+3, ..)
for (int sumaLoopCounter = 1; sumaLoopCounter <= loopsCounter; sumaLoopCounter++){
//simply make sum with the given number
/* first step 0 +1
second 1+2 added to previous suma = 1+3
third 1+2+3,.. added to previous = 4+6
...
*/
sum += sumaLoopCounter;
//just testing for demonstration
iterations++; //iterations = iterations + 1
}
}
printf("%i \n",iterations);
printf("%i",sum);
然后您将获得预期的输出-所有“括号元素”和10次迭代的总和,这些迭代与所需添加项的数量匹配
10
20
答案 2 :(得分:0)
这里是一个循环;非常快。
#include <stdio.h>
int cumulative_sum(int m)
{
int sum = 0;
for(int n=1; n<=m; ++n) sum += n*(n+1);
return sum/2;
}
int main(void)
{
int n;
printf("Input value N: ");
scanf("%d", &n);
printf("Answer is %d\n", cumulative_sum(n));
return 0;
}