首先,5 不被视为列表的一部分,它是列表的计数。因此,它不应包含在计算中。
因为这是作业,所以这里是伪代码。你的工作是首先理解伪代码(使用示例输入在你的脑海中运行它)然后将其转换为 C 代码并尝试让它编译并成功运行(使用相同的示例输入)。
我建议将样本输入“2 7 3”(两个项目,分别是 7 和 3)作为一个好的起点,因为它很小,总和为 10,最小的 3。
如果您尝试这样做超过一天,请将您的代码发布到此问题中作为编辑,我们会看看我们能做些什么来帮助您。
get a number into quantity
set sum to zero
loop varying index from 1 to quantity
get a number into value
add value to sum
if index is 1
set smallest to value
else
if value is less than smallest
set smallest to value
endif
endif
endloop
output "The sum of the sequence of integers is: ", sum
output "The smallest of the integers entered is: ", smallest
Stack Overflow 似乎分为三个阵营,那些只会给你代码的阵营,那些会告诉你推迟并完成自己的作业的阵营,以及像我这样更愿意看到你接受教育的阵营 - 由当你进入劳动力市场时,我希望退休,这样你就不会与 me 竞争 :-)。
在任何人发现我的算法中的漏洞之前,这是为了教育。我至少留下了一个陷阱来帮助训练这个家伙 - 可能还有其他人,我会声称我故意把它们放在那里是为了测试他:-)。
更新:
罗伯特,在我已经评论过你的(非常好的)尝试之后,这就是我修改你的代码来完成任务的方式(当然是你的,而不是我的)。您有望看到我的 cmets 如何修改代码以达到此解决方案:
#include <stdio.h>
int main (int argCount, char *argVal[]) {
int i; // General purpose counter.
int smallNum; // Holds the smallest number.
int numSum; // Holds the sum of all numbers.
int currentNum; // Holds the current number.
int numCount; // Holds the count of numbers.
// Get count of numbers and make sure it's in range 1 through 50.
printf ("How many numbers will be entered (max 50)? ");
scanf ("%d", &numCount);
if ((numCount < 1) || (numCount > 50)) {
printf ("Invalid count of %d.\n", numCount);
return 1;
}
printf("\nEnter %d numbers then press enter after each entry:\n",
numCount);
// Set initial sum to zero, numbers will be added to this.
numSum = 0;
// Loop, getting and processing all numbers.
for (i = 0; i < numCount; i++) {
// Get the number.
printf("%2d> ", i+1);
scanf("%d", ¤tNum);
// Add the number to sum.
numSum += currentNum;
// First number entered is always lowest.
if (i == 0) {
smallNum = currentNum;
} else {
// Replace if current is smaller.
if (currentNum < smallNum) {
smallNum = currentNum;
}
}
}
// Output results.
printf ("The sum of the numbers is: %d\n", numSum);
printf ("The smallest number is: %d\n", smallNum);
return 0;
}
这是您的示例数据的输出:
pax> ./qq
How many numbers will be entered (max 50)? 5
Enter 5 numbers then press enter after each entry:
1> 100
2> 350
3> 400
4> 550
5> 678
The sum of the numbers is: 2078
The smallest number is: 100
pax> ./qq
How many numbers will be entered (max 50)? 5
Enter 5 numbers then press enter after each entry:
1> 40
2> 67
3> 9
4> 13
5> 98
The sum of the numbers is: 227
The smallest number is: 9
pax> ./qq
How many numbers will be entered (max 50)? 0
Invalid count of 0.
[fury]$ ./qq
How many numbers will be entered (max 50)? 51
Invalid count of 51.
顺便说一句,请确保您始终将 cmets 添加到您的代码中。教育工作者喜欢这种东西。必须在 10 年后尝试理解您的代码的开发人员也是如此。