简体   繁体   中英

C Programming - Collecting data in a function outside of main()

Write a program that asks the user to enter daily rainfall amounts. Your program will need to accept 5 daily rainfall inputs. Only allow non-negative rainfall amounts. When the user enters a negative number, tell them that the number is invalid, and that they should enter another, valid value.

Calculate the total rainfall and the average rainfall. Determine the largest daily rainfall and the smallest daily rainfall.

Output the total, average, largest, and smallest values using informative messages.

The following things cannot happen in main:

  1. Accepting user input
  2. Calculation of total or average
  3. Determination of largest or smallest
  4. Outputting results

=============================================

Right now i'm just trying to figure out how to enter the 5 numbers, I have this code so far but it's having me put it in an infinite amount of times. I've been working on this project for hours, so any advice would be amazing.

#include <stdio.h>
#include <stdlib.h>
#define SIZE 5 // have the user enter it 5 times

double CollectRainfall() {
    double amount;
    double rainfall[SIZE];
    int i;

    printf("Enter a rainfall amount: \n");  // enter amount
    scanf_s("%lf", &amount);

    for (i = 0; i < SIZE; i++) {
        rainfall[i] = CollectRainfall();
        while (amount < 0.0) {  // if it's a negative number
            printf("The number is invalid.\n");  // display error message if a negative # was entered
            printf("Enter another rainfall amount: \n");
        }
    }

}   
int main() {

    CollectRainfall();

    return 0;
}  

You can create a struct to store you data and do the operation.

Something like:

#include <stdio.h>
#include <stdlib.h>
#define SIZE 5 // have the user enter it 5 times


typedef struct data {
    double rainfall[SIZE];
    double average;
    double min;
    double max;
} data_t;

static void collectRainfall(double rainfall[SIZE]) {
    for (int i = 0; i < SIZE; i++) {
        double amount;

        printf("Enter a rainfall amount: \n");  // enter amount
        scanf("%lf", &amount);
        while (amount < 0.0) {  // if it's a negative number
            printf("The number is invalid.\n");  // display error message if a negative # was entered
            printf("Enter a rainfall amount: \n");  // enter amount
            scanf("%lf", &amount);
        }
        rainfall[i] = amount;
    }
}

static void compute(data_t *data) {
     data->min = data->rainfall[0];
     data->max = data->rainfall[0];
     data->average = data->rainfall[0];

     for (int i = 1; i < SIZE; i++) {
         double rainfall = data->rainfall[i];
         if (rainfall > data->max) {
             data->max = rainfall;
         }
         if (rainfall < data->min) {
             data->min = rainfall;
         }
         data->average += rainfall;
     }
     data->average /= SIZE;
}

static void display(data_t *data) {
    printf("min %f, max %f, average %f\n",
            data->min, data->max, data->average);
}

int main() {
    data_t data;

    collectRainfall(data.rainfall);
    compute(&data);
    display(&data);

    return 0;
}

scanf is a pain in case of bad input best is to read a line then parse it, check if strtod is ok

static void collectRainfall(double rainfall[SIZE]) {
    for (int i = 0; i < SIZE; i++) {
        char str[32];
        double amount = -1;

        printf("Enter a rainfall amount [%d/%d]: \n", i , SIZE);  
        while (42) {
            char *res = fgets(str, sizeof(str), stdin);
            if (res && (amount = strtod(str, &res)) >= 0 && res != str)
                break;
            printf("The number is invalid.\n");
            printf("Enter a rainfall amount [%d/%d]: \n", i , SIZE);  
        }
        rainfall[i] = amount;
    }
}

As said the recursion as you have it will essentially create an infinite loop, and really, for this you dont need it either, you can do something like:

Running sample (commented changes)

#include <stdio.h>
#include <stdlib.h>

#define SIZE 5 // have the user enter it 5 times

void CollectRainfall() { //no return needed

    double rainfall[SIZE], sum = 0, max = 0, min = 0;
    int i;


    for (i = 0; i < SIZE; i++)
    {
        printf("Enter a rainfall amount: \n"); // enter amount
        scanf("%lf", &rainfall[i]); //save values into the array
        while (rainfall[i] < 0.0)
        {                                       // if it's a negative number
            printf("The number is invalid.\n"); // display error message if a negative # was entered
            printf("Enter another rainfall amount: \n");
            i--; // iterate back to replace negative number
        }
    }
    printf("Values:");
    for (i = 0, min = rainfall[i]; i < SIZE; i++)
    {
        printf(" %.2lf", rainfall[i]); // print all values
        sum += rainfall[i];          // sum values
        if(rainfall[i] > max){       //max value
            max = rainfall[i];      
        }
        if(min > rainfall[i]){       //min value
            min = rainfall[i];
        }
    }
    printf("\nSum: %.2lf", sum);            // print sum
    printf("\nMax: %.2lf", max);            // print max
    printf("\nMin: %.2lf", min);            // print min
    printf("\nAverage: %.2lf", sum / SIZE); //print average
}

int main() {
    CollectRainfall();
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM