简体   繁体   中英

Finding the Average in a sequence of number in c while ignoring the negative numbers in the sequence

I have to write a C program that reads a sequence of integers (positive, negative, or zero) and calculate the average of the positive integers only . If there are no positive numbers, you should display the following statement followed by a new line No positive numbers!

Here is my code, I just need help with how to ignore the negative numbers in the input sequence.

#include<stdio.h>

int main(){

    int num;  //number of elements
    int i;
    int sequence[100];  //numeber if sequence
    int sum = 0.0;            //sum if the sequence
    float avg;          // the average

    printf("Enter the number of number in the sequence:\n");
    scanf("%d", &num);

    while (num < 0 || sequence[num] < 0) {
        printf("No positine numbers!\n");
    }

    printf("Enter the sequence:\n");
    for (i=0; i < num; i++) {
        scanf("%d", &sequence[i]);
        sum += sequence[i];
    }

    avg = (float) sum / num;
    printf("Average is %.2f\n", avg);
    return(0);
}

If you want the average of the positive numbers, you should use a different variable than num for your final avg calculation.

I would do something like this:

    int PositiveNumCount = 0;
    float avg;   
    for (i=0; i < num; i++) {
        scanf("%d", &sequence[i]);
        if(sequence[i] > 0){ sum += sequence[i]; PositiveNumCount++;}
    }
    avg = (float) sum / PositiveNumCount;

There are multiple problems in your code:

  • sequence[num] may refer to an entry beyond the end of the array which has undefined behavior, and otherwise reads from an uninitalized array, which has undefined behavior too. Just remove this test completely as it is useless.
  • you do not need to store the numbers read, just read them ne at a time into a temporary variable and only add and count the positive values.
  • you should test the return value of scanf to avoid undefined behavior on invalid input.

Here is a corrected and simplified version:

#include <stdio.h>

int main() {
    int num;           // max number of values to read
    int count = 0;     // number of positive values
    double sum = 0.0;  // sum if the sequence
    double avg;        // the average

    printf("Enter the number of number in the sequence:\n");
    if (scanf("%d", &num) == 1 && num > 0) {
        printf("Enter the sequence:\n");
        while (num-- > 0) {
            int temp;
            if (scanf("%d", &temp) != 1)
                break;
            if (temp >= 0) {
                sum += temp;
                count++;
            }
        }
        avg = sum / count;
        printf("Average is %.2f\n", avg);
    }
    return 0;
}

Here:

while (num < 0 || sequence[num] < 0) {

you are testing sequence[num] before you have written any values to the array, and the test of num should be num <= 0 since if there are zero values, there are also no positive values. You can only decide that there are no positive values after you have entered them all.

The array sequence is unnecessary - you can simply accumulate the positive values to sum and discard them, maintaining a count of valid values. The avoids any buffer overrun issues also.

sum is an int , but you have unnecessarily initialised it with a double .

Your average calculation:

avg = (float) sum / num ;

is incorrect since num includes negative values - you need a separate count of valid values contributing to the average (unless the intent is to treat all negative values as zero).

Another issue is that you have not validated the input matched the format specifier.

int main()
{
    printf("Enter the number of number in the sequence:\n");
    int num = 0 ;
    int check = scanf( "%d", &num ) ;

    int positive_count = 0 ;
    int sum = 0 ;
    if( check != 0 && num >= 0 )
    {
        printf( "Enter the sequence:\n" ) ;

        int i = 0 ;
        while( i < num ) 
        {
            int value = 0 ;
            check = scanf( "%d", &value ) ;
            if( check != 0 )
            {
                i++ ;
                if( value >= 0 )
                {
                    positive_count++ ;
                    sum += value ;
                }
            }
        }
    }

    if( positive_count != 0 )
    {
        float avg = (float) sum / positive_count ;

        printf( "Average is %.2f\n", avg ) ;
    }
    else
    {
        printf( "No positive numbers!\n" ) ;
    }

    return 0 ;
}
printf("Enter the sequence:\n");
for (i=0; i < num; i++) {
    scanf("%d", &sequence[i]);
    if(sequeunce[i] > 0){ //This if statement is what your looking for, but there are several other problems in your code.  GL!
        sum += sequence[i];
    }
}

The above if statement is what the OP was asking for: "Here is my code, I just need help with how to ignore the negative numbers in the input sequence."

There are many issues with his posted code, including using variables before they are initialized and infinite looping paths. This is the shortest answer to his question.

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