编写一个程序,对整数序列以及序列中的最小值求和

时间:2022-10-11 19:58:45

Write a program that sums the sequence of integers as well as the smallest in the sequence. Assume that the first integer read with scanf specifies the number of values remaining to be entered. For example the sequence entered:

编写一个程序,对整数序列和序列中的最小值求和。假设使用scanf读取的第一个整数指定了要输入的剩余值的数量。例如输入的序列:

Input: 5 100 350 400 550 678

输入:5 100 350 400 550 678

Output: The sum of the sequence of integers is: 2078

输出:整数序列的总和为:2078

Input: 5 40 67 9 13 98

输入:5 40 67 9 13 98

Output: The smallest of the integers entered is: 9

输出:输入的最小整数是:9

This is a daily problem I am working on but by looking at this, Isnt 5 the smallest integer? I have no idea how to write this program. Appreciate any help

这是我正在研究的日常问题,但通过观察,Isnt 5是最小的整数?我不知道如何编写这个程序。感谢任何帮助

8 个解决方案

#1


First thing, the 5 is not considered part of the list, it's the count for the list. Hence it shouldn't be included in the calculations.

首先,5不被视为列表的一部分,它是列表的计数。因此,它不应包括在计算中。

Since this is homework, here's the pseudo-code. Your job is to understand the pseudo-code first (run it through your head with sample inputs) then turn this into C code and try to get it compiling and running successfully (with those same sample inputs).

由于这是家庭作业,这里是伪代码。你的工作是首先理解伪代码(通过样本输入运行它)然后将其转换为C代码并尝试使其成功编译并运行(使用相同的样本输入)。

I would suggest the sample input of "2 7 3" (two items, those being 7 and 3) as a good start point since it's small and the sum will be 10, smallest 3.

我建议将样本输入“2 7 3”(两个项目,即7和3)作为一个良好的起点,因为它很小,总和将是10,最小3。

If you've tried to do that for more than a day, then post your code into this question as an edit and we'll see what we can do to help you out.

如果您已尝试超过一天,请将您的代码作为编辑发布到此问题中,我们会看到我们可以做些什么来帮助您。

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 seems to be divided into three camps, those that will just give you the code, those that will tell you to push off and do your own homework and those, like me, who would rather see you educated - by the time you hit the workforce, I hope to be retired so you won't be competing with me :-).

Stack Overflow似乎分为三个阵营,那些只会给你代码的那些,那些会告诉你推卸并做自己的功课,以及那些像我一样宁愿看到你受过教育的人 - 当你点击时劳动力,我希望退休,所以你不会与我竞争:-)。

And before anyone picks holes in my algorithm, this is for education. I've left at least one gotcha in it to help train the guy - there may be others and I will claim I put them there intentionally to test him :-).

在任何人在我的算法中选择漏洞之前,这是用于教育。我已经留下了至少一个问题来帮助训练那个人 - 可能还有其他人我会声称我故意将他们放在那里测试他:-)。


Update:

Robert, after your (very good) attempt which I've already commented on, this is how I'd modify your code to do the task (hand yours in of course, not mine). You can hopefully see how my comments modify the code to reach this solution:

罗伯特,在你已经评论过的(非常好的)尝试之后,这就是我修改你的代码来完成任务的方式(当然,不是我的)。您可以希望看到我的评论如何修改代码以达到此解决方案:

#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", &currentNum);

        // 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;
}

And here is the output from your sample data:

以下是样本数据的输出:

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.

By the way, make sure you always add comments to your code. Educators love that sort of stuff. So do developers that have to try to understand your code 10 years into the future.

顺便说一下,请确保始终为代码添加注释。教育工作者喜欢那种东西。开发人员也必须在未来10年内尝试理解您的代码。

#2


Read:

Assume that the first integer read with scanf specifies the number of values remaining to be entered

假设使用scanf读取的第一个整数指定了要输入的剩余值的数量

so it's not part of the sequence...

所以它不是序列的一部分......

for the rest, it's your homework (and C...)

其余的,这是你的作业(和C ...)

#3


No. 5 is the number of integers you have to read into the list.

第5号是您必须在列表中读取的整数数。

#4


Jeebus, I'm not doing your homework for you, but...

Jeebus,我不是在为你做功课,但......

Have you stopped to scratch this out on paper and work out how it should work? Write some pseudo-code and then transcribe to real code. I'd have thought:

你有没有停止在纸上划出这个并弄清楚它应该如何工作?编写一些伪代码,然后转录为真实代码。我想过:

  • Read integer
  • Loop that many times ** Read more integers ** Add ** Find Smallest
  • 循环多次**阅读更多整数**添加**查找最小值

IF you're in C look at INT_MAX - that will help out finding the smallest integer.

如果您在C中查看INT_MAX - 这将有助于找到最小的整数。

#5


Since the list of integers is variable, I'd be tempted to use strtok to split the string up into individual strings (separate by space) and then atoi to convert each number and sum or find minimum on the fly.

由于整数列表是可变的,我很想使用strtok将字符串拆分为单独的字符串(按空格分隔),然后使用atoi转换每个数字和总和或在运行中找到最小值。

-Adam

#6


First you read the number of values (ie. 5), then create an array of int of 5 elements, read the rest of the input, split them and put them in the array (after converting them to integers).

首先,您读取值的数量(即5),然后创建一个包含5个元素的int数组,读取其余的输入,拆分它们并将它们放入数组中(将它们转换为整数后)。

Then do a loop on the array to get the sum of to find the smallest value.

然后在数组上执行循环以获得找到最小值的总和。

Hope that helps

希望有所帮助

#7


wasn[']t looking for you guys to do the work

我没有找你们做这项工作

Cool. People tend to take offense when you dump the problem text at them and the problem text is phrased in an imperative form ("do this! write that! etc.").

凉。当你将问题文本转储给他们时,人们往往会冒犯,问题文本是以命令式形式表达的(“做这个!写那个!等等”)。

You may want to say something like "I'm stuck with a homework problem. Here's the problem: write a [...]. I don't understand why [...]."

你可能想说“我遇到了家庭作业问题。这就是问题:写一个[...]。我不明白为什么[...]。”

#8


#include <stdio.h>

main ()
{
    int num1, num2, num3, num4, num5, num6, i;
    int smallestnumber=0;
    int sum=0;
    int numbers[50];
    int count;
    num1 = 0;
    num2 = 0;
    num3 = 0;
    num4 = 0;
    num5 = 0;
    num6 = 0;

    printf("How many numbers will be entered (max 50)? ");
    scanf("%d", &count);

    printf("\nEnter %d numbers then press enter after each entry:  \n", count);

    for (i=0; i < count; i++) {
        printf("%2d> ", i+1);
        scanf("%d", &numbers[i]);
        sum +=  numbers[i];
    }

    smallestnumber = numbers[0];
    for (i=0; i < count; i++) {
        if ( numbers[i] < smallestnumber)
        {
            smallestnumber = numbers[i];
        }
    }

    printf("the sum of the numbers is: %d\n", sum);
    printf("The smallest number is: %d", smallestnumber);
}

#1


First thing, the 5 is not considered part of the list, it's the count for the list. Hence it shouldn't be included in the calculations.

首先,5不被视为列表的一部分,它是列表的计数。因此,它不应包括在计算中。

Since this is homework, here's the pseudo-code. Your job is to understand the pseudo-code first (run it through your head with sample inputs) then turn this into C code and try to get it compiling and running successfully (with those same sample inputs).

由于这是家庭作业,这里是伪代码。你的工作是首先理解伪代码(通过样本输入运行它)然后将其转换为C代码并尝试使其成功编译并运行(使用相同的样本输入)。

I would suggest the sample input of "2 7 3" (two items, those being 7 and 3) as a good start point since it's small and the sum will be 10, smallest 3.

我建议将样本输入“2 7 3”(两个项目,即7和3)作为一个良好的起点,因为它很小,总和将是10,最小3。

If you've tried to do that for more than a day, then post your code into this question as an edit and we'll see what we can do to help you out.

如果您已尝试超过一天,请将您的代码作为编辑发布到此问题中,我们会看到我们可以做些什么来帮助您。

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 seems to be divided into three camps, those that will just give you the code, those that will tell you to push off and do your own homework and those, like me, who would rather see you educated - by the time you hit the workforce, I hope to be retired so you won't be competing with me :-).

Stack Overflow似乎分为三个阵营,那些只会给你代码的那些,那些会告诉你推卸并做自己的功课,以及那些像我一样宁愿看到你受过教育的人 - 当你点击时劳动力,我希望退休,所以你不会与我竞争:-)。

And before anyone picks holes in my algorithm, this is for education. I've left at least one gotcha in it to help train the guy - there may be others and I will claim I put them there intentionally to test him :-).

在任何人在我的算法中选择漏洞之前,这是用于教育。我已经留下了至少一个问题来帮助训练那个人 - 可能还有其他人我会声称我故意将他们放在那里测试他:-)。


Update:

Robert, after your (very good) attempt which I've already commented on, this is how I'd modify your code to do the task (hand yours in of course, not mine). You can hopefully see how my comments modify the code to reach this solution:

罗伯特,在你已经评论过的(非常好的)尝试之后,这就是我修改你的代码来完成任务的方式(当然,不是我的)。您可以希望看到我的评论如何修改代码以达到此解决方案:

#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", &currentNum);

        // 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;
}

And here is the output from your sample data:

以下是样本数据的输出:

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.

By the way, make sure you always add comments to your code. Educators love that sort of stuff. So do developers that have to try to understand your code 10 years into the future.

顺便说一下,请确保始终为代码添加注释。教育工作者喜欢那种东西。开发人员也必须在未来10年内尝试理解您的代码。

#2


Read:

Assume that the first integer read with scanf specifies the number of values remaining to be entered

假设使用scanf读取的第一个整数指定了要输入的剩余值的数量

so it's not part of the sequence...

所以它不是序列的一部分......

for the rest, it's your homework (and C...)

其余的,这是你的作业(和C ...)

#3


No. 5 is the number of integers you have to read into the list.

第5号是您必须在列表中读取的整数数。

#4


Jeebus, I'm not doing your homework for you, but...

Jeebus,我不是在为你做功课,但......

Have you stopped to scratch this out on paper and work out how it should work? Write some pseudo-code and then transcribe to real code. I'd have thought:

你有没有停止在纸上划出这个并弄清楚它应该如何工作?编写一些伪代码,然后转录为真实代码。我想过:

  • Read integer
  • Loop that many times ** Read more integers ** Add ** Find Smallest
  • 循环多次**阅读更多整数**添加**查找最小值

IF you're in C look at INT_MAX - that will help out finding the smallest integer.

如果您在C中查看INT_MAX - 这将有助于找到最小的整数。

#5


Since the list of integers is variable, I'd be tempted to use strtok to split the string up into individual strings (separate by space) and then atoi to convert each number and sum or find minimum on the fly.

由于整数列表是可变的,我很想使用strtok将字符串拆分为单独的字符串(按空格分隔),然后使用atoi转换每个数字和总和或在运行中找到最小值。

-Adam

#6


First you read the number of values (ie. 5), then create an array of int of 5 elements, read the rest of the input, split them and put them in the array (after converting them to integers).

首先,您读取值的数量(即5),然后创建一个包含5个元素的int数组,读取其余的输入,拆分它们并将它们放入数组中(将它们转换为整数后)。

Then do a loop on the array to get the sum of to find the smallest value.

然后在数组上执行循环以获得找到最小值的总和。

Hope that helps

希望有所帮助

#7


wasn[']t looking for you guys to do the work

我没有找你们做这项工作

Cool. People tend to take offense when you dump the problem text at them and the problem text is phrased in an imperative form ("do this! write that! etc.").

凉。当你将问题文本转储给他们时,人们往往会冒犯,问题文本是以命令式形式表达的(“做这个!写那个!等等”)。

You may want to say something like "I'm stuck with a homework problem. Here's the problem: write a [...]. I don't understand why [...]."

你可能想说“我遇到了家庭作业问题。这就是问题:写一个[...]。我不明白为什么[...]。”

#8


#include <stdio.h>

main ()
{
    int num1, num2, num3, num4, num5, num6, i;
    int smallestnumber=0;
    int sum=0;
    int numbers[50];
    int count;
    num1 = 0;
    num2 = 0;
    num3 = 0;
    num4 = 0;
    num5 = 0;
    num6 = 0;

    printf("How many numbers will be entered (max 50)? ");
    scanf("%d", &count);

    printf("\nEnter %d numbers then press enter after each entry:  \n", count);

    for (i=0; i < count; i++) {
        printf("%2d> ", i+1);
        scanf("%d", &numbers[i]);
        sum +=  numbers[i];
    }

    smallestnumber = numbers[0];
    for (i=0; i < count; i++) {
        if ( numbers[i] < smallestnumber)
        {
            smallestnumber = numbers[i];
        }
    }

    printf("the sum of the numbers is: %d\n", sum);
    printf("The smallest number is: %d", smallestnumber);
}