编写一个程序,对整数序列和序列中的最小值求和.假设使用scanf读取的第一个整数指定剩余要输入的值的数量.例如输入的序列:
输入:5 100 350 400 550 678
输出:整数序列的总和是:2078
输入:5 40 67 9 13 98
输出:输入的最小整数是:9
这是我正在研究的日常问题,但通过观察,Isnt 5是最小的整数?我不知道如何编写这个程序.感谢任何帮助
pax*_*blo 19
首先,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
Run Code Online (Sandbox Code Playgroud)
Stack Overflow似乎分为三个阵营,那些只会给你代码的那些,那些会告诉你推卸并做自己的功课,以及那些像我一样宁愿看到你受过教育的人 - 当你点击时劳动力,我希望退休,所以你不会与我竞争:-).
在任何人在我的算法中选择漏洞之前,这是用于教育.我已经留下了至少一个问题,以帮助训练这个人 - 可能还有其他人,我会声称我故意将他们放在那里测试他:-).
更新:
罗伯特,在你已经评论过的(非常好的)尝试之后,这就是我修改你的代码来完成任务的方式(当然,不是我的手).您可以希望看到我的评论如何修改代码以达到此解决方案:
#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;
}
Run Code Online (Sandbox Code Playgroud)
以下是样本数据的输出:
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.
Run Code Online (Sandbox Code Playgroud)
顺便说一下,请确保始终为代码添加注释.教育工作者喜欢那种东西.因此,开发人员必须在未来10年内尝试理解您的代码.