C编程: Trouble summing numbers entered by the user with for loop

标签 c loops for-loop sum

因此,我必须编写一个程序来询问用户一个整数,然后该整数将确定用户在添加所有输入的数字之前还可以获得多少个条目。因此,如果第一个输入的整数是“5”,则用户可以再输入 5 个整数。然后将这 5 个整数在最后相加并显示。我编写了一个带有 for 循环的程序,但由于某种原因,它只添加前 4 个整数,而不是第 5 个整数。这是代码:

int main() { //declare main function

       int c=0,n,i; //declare integers
       int sum=0;

       printf("\nEnter an integer: "); //ask user for input and create a label
       scanf("%d",&n);


       if (n>=0) { //use if statement

           for (i=0;i<n;i++) //use for loop inside if statement to account for negative integers

           {
               sum+=c;
               printf("Enter an integer: ");
               scanf("%d",&c);
           }

       }

       else {

           printf("Wrong number. You can only enter positive integers!");

       }


       printf("The sum of the %d numbers entered is: %d",i,sum);

       return 0;
}

最佳答案

只需改变

的位置即可
sum+=c; 

在 scanf 之后它应该可以工作。

关于C编程: Trouble summing numbers entered by the user with for loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54388404/

相关文章:

c - 逗号分隔的表达式作为 for 循环中的条件如何工作?

c - 给 float 变量赋值会改变 C 中的值

c - fgets 在 C linux 中不工作

javascript - HTML5 Canvas 游戏开发复杂化

list - TCL:循环如何从最内层循环到外部?

python - 计算 H2o 中的 MAPE : Error: Provided column type POSIXct is unknown

替换 for 循环,但是用哪个 apply 语句呢?

python - 与 Python 相对,用于 ... else

c - 接收UDP数据时移动OpenGL机械臂?

c - 不接受用户输入的其他选项