因此,我必须编写一个程序来询问用户一个整数,然后该整数将确定用户在添加所有输入的数字之前还可以获得多少个条目。因此,如果第一个输入的整数是“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/