Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Average of # Sequence

Tags:

c

I'm having trouble figuring out the loop in the average function. User enters sequence and if the number of numbers in the sequence is greater than 0, output avg of the numbers and repeat for another sequence. If the sequence has no numbers, exit program.

I understand that I'm telling the average function to return 0 when sum = 0 and that's why it exits after the 1st sequence (I think).

Any suggestions as to how to avoid that? Pseudocode if possible!

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

double average();

int main () 
{
    while( average() ) 
    {
    }
}//end main

double average() 
{
    double n, sum = 0;
    int count = 0;

    printf ( "Enter sequence: " );
    while( scanf( "%lf", &n ) )
    {
        sum += n;
        count++;
    }

    if( sum > 0 )
    {
        printf( "average is %.2f\n", sum/(double)count );
        return 1;
    }
    else
        return 0;
    }
}

Here is my output:

Enter sequence: 3 4 5 x
    average: 4.00
Enter sequence: Press any key to continue . . .
like image 935
seeholz Avatar asked May 06 '26 10:05

seeholz


1 Answers

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

int average(void);

int main(void) 
{
    while (average()) 
        ;
    return 0;
}

int average(void) 
{
    double n, sum = 0;
    int count = 0;

    printf("Enter sequence: ");
    while (scanf( "%lf", &n ) == 1)
    {
        sum += n;
        count++;
    }
    int c;
    while ((c = getchar()) != EOF && c != '\n')
        ;

    if (sum > 0)
    {
        printf("average is %.2f\n", sum / count);
        return 1;
    }
    else
        return 0;
}

This reads anything on the line up to the newline after a conversion fails, thus setting you up for reading the next sequence. The loop test for scanf() is improved; it will exit on EOF, too. The cast in the division was unnecessary; the compiler has to convert count to double because sum is a double, even without you telling it to do so explicitly. The return type of average() is not a double; it is a boolean, which is classically spelled int. In C99 or later (which the code assumes you have; if you don't, you're stuck on Windows and need to move int c; to the top of the function), then you could #include <stdbool.h> and use a return type of bool and replace return 1; by return true; and replace return 0; by return false;.

like image 147
Jonathan Leffler Avatar answered May 08 '26 00:05

Jonathan Leffler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!