Average, max, and min program in C

前端 未结 8 681
梦毁少年i
梦毁少年i 2021-01-21 02:55

So I\'m coding in C, and I need to come up with code that will take n numbers from the user, and find their minimum, maximum, average, and sum of squares for for their values. S

8条回答
  •  温柔的废话
    2021-01-21 03:00

    Your algorithm is not quite right. Below is the correct implementation:

    #include 
    #include 
    #include 
    
    int main(void)
    {
        float average;
        int n, num, count = 0, sum = 0, squaresum = 0;
        int min = INT_MAX, max = INT_MIN;
        bool gotAnswer = false;
    
        /* Don't Let User Enter Wrong Input */
        while(!gotAnswer)
        {
            printf("Please enter the number of numbers you wish to evaluate: ");
            if(scanf_s("%d", &n) != 1)
            {
                /* User Entered Wrong Input; Clean Up stdin Stream*/
                while(getchar() != '\n')
                {
                     continue;
                }
            }
            else
            {
                /* User Input Was Good */
                gotAnswer = true;
            }
        }
    
        /* Clear stdin Stream Just In Case */
        while(getchar() != '\n')
            continue;
    
        while(count < n)
        {
            /* Don't Let User Enter Wrong Input */
            gotAnswer = false;
            printf("Enter number %d: ", count + 1);
            if(scanf_s("%d", &num) != 1)
            {
                /* User Entered Wrong Input; Clean Up stdin Stream */
                while(getchar() != '\n')
                    continue;
    
                /* Let User Try Again */
                continue;
            }
            else
            {
                /* User Input Was Correct */
                gotAnswer = true;
    
                /* Clear stdin Stream Just In Case */
                while(getchar() != '\n')
                    continue;
            }
    
            if(num > max)
                max = num;
            if(num < min)
                min = num;
    
            sum += num;
            squaresum += num * num;
            count++;
        }
    
        average = 1.0 * sum / n;
    
        printf("Your average is %.2f\n", average);
        printf("The sum of your squares is %d\n", squaresum);    
        printf("Your maximum number is %d\n", max);
        printf("Your minimum number is %d\n", min);
    
        system("pause");
        return 0;
    }
    

    I've added error checking and recovery. Please ask if you have any questions about the logic.

提交回复
热议问题