简体   繁体   中英

Printing sum of digits greater than average

For an assignment, I have to write a code in C that prints the digits from a number that are greater than its average.

I already wrote some code, but when I insert a single number or a number with the same digits (like 555), it does not give me an answer. It should give, in the case of 555 --> 5 (and 8 -> 8, 77 -> etc.)

The code I wrote is:

(I've commented at every step I take.)

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

int main (int argc, char *v[])  {
    /* imput: 1 number between 1 and 2.000.000.000 */
    int n;          /*  stores the value                            */
    int ext, ext2;  /*  stores a copy of the number                 */
    int rem;        /*  stores the remainders                       */
    int tot;        /*  stores the total of the digits              */
    int avg;        /*  stores the average of the digits            */
    int i;          /*  counts the amount of digits                 */
    int big;        /*  stores the biggest and second biggest value */

    scanf("%d", &n);

    /* seperate digits and add them */
    ext=n;
    ext2=n;
    tot=0;
    big=0;
    avg=0;
    i=0;

    while(ext!=0 && n<2000000000 && n>=1){
        rem=ext%10;
        tot=tot+rem;
        ext=ext/10;
        i++;
    };  

    /* average value */
    avg=tot/i;      

    /* find and print higher numbers */
    while (ext2>0){
        rem = ext2 % 10;
        if (rem > avg){
            big += rem;
        };
        ext2 = ext2 / 10;
    }

    if(n<100 && n>9){
        printf("%d\n", big);
    } else if(big==avg){
        printf("%d\n", 0);
    } else if(big>=avg){
        printf("%d\n", big);
    };

    return 0;
}

Hope someone can help me!

You forgot to initialize variable i with 0. I've corrected your code and it gives expected outcome. And the answer is 0 for a single number because the average of one number is always the number itself so the number is never greater than the average.

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

int main ()
{
    /* imput: 1 number between 1 and 2.000.000.000 */
    int n;          /*  stores the value                            */
    int ext, ext2;  /*  stores a copy of the number                 */
    int rem, rem2;  /*  stores the remainders                       */
    long tot;       /*  stores the total of the digits              */
    int avg;        /*  stores the average of the digits            */
    int i;          /*  counts the amount of digits                 */
    int big, big2;  /*  stores the biggest and second biggest value */
    int sum;        /*  stores sum of digits greater than average   */
    scanf("%d", &n);

    /* seperate digits and add them */
    ext=n;
    ext2=n;
    tot=0;
    big=0;
    big2=0;
    avg=0;
    i=0;
    sum=0;

    while(ext!=0 && n<2000000000 && n>=1)
    {
        rem=ext%10;
        tot=tot+rem;
        ext=ext/10;
        i++;
    };

    /* average value */
    avg=tot/i;

    /* find and print higher numbers */

    while(ext2>0)
    {
        rem2=ext2%10;
        if(rem2>avg)
        {
            sum+=rem2;
        };
        ext2=ext2/10;
    };

    printf("sum of digits greater than average: %d",sum);

    return 0;
}

In addition to failing to initialize i = 0; prior to i++; , your biggest problem is you are confusing yourself with the large number of unnecessary and nondescript variable names. ext, ext2, tot, big, big2, avg, rem, rem2 is just variable salad.

While you will need ext2 to hold a copy of the variable you reduce by % (modulo) to find tot and avg , there is no need for rem2 or big2 (you can simply reuse rem ) and you only need one big (presuming that is your variable holding the sum of digits greater than avg )

Further, your loop to find big (and using big2 ) is wildly more confusing than it need be. You don't care if rem2 is greater than big2 and then setting big2 = rem2; what you care about is whether the digit is larger than avg . (that's it) All you need is:

    /* find and print higher numbers */
    while (ext2>0){
        rem = ext2 % 10;
        if (rem > avg){
            big += rem;
        };
        ext2 = ext2 / 10;
    }

Now big holds the sum of digits larger than averages.

Reusing variables and using descriptive variable names will go a long way to keeping your logic straight and prevent unnecessary variable sprawl. There is a normal rule-of-thumb to keep in mind when writing functions (it is good to keep in mind always), but if you are writing a function and you find yourself using more than 4-variables, you may need to refactor your program. (it's not a hard rule, but the crux of it is to prevent exactly the variable salad you fell into)

Why long tot; ? At the very most 1+9+9+9+9+9+9+9+9+9 = 82 . The use of int like you use for the rest of your variables is fine. (given your constraint that 1≤n<2000000000 )

Lastly, while you can take the input numerically as you have and use modulo to extract each digit, it would be far simpler just to read the input as a string and then simply iterate over each character subtracting '0' to get the numeric value (as suggested in the comments by Weather Vane)

Edit Tidying Up Variables

From our continued discussion, I've decided to drop a quick edit that tidies the rest of the code up a bit and reduces the number of variables, as well as initializing the variables when they are declared. You could do something similar to:

#include <stdio.h>

int main (void)  {

    int n,          /*  stores the value                                */
        tmp,        /*  stores a copy of the number                     */
        rem,        /*  stores the remainders                           */
        tot = 0,    /*  stores the total of the digits                  */
        avg = 0,    /*  stores the average of the digits                */
        digits = 0, /*  counts the number of digits                     */
        big = 0;    /*  stores the sum of digits larger than avg        */

    /* imput: 1 number (1 <= n && n <= 2.000.000.000    */
    if (scanf("%d", &n) != 1) { /* read/validate number */
        fputs ("error: invalid integer input.\n", stderr);
        return 1;
    }
    if (n < 1 || 2000000000 < n) {  /* validate n in allowable range */
        fputs ("error: input outside allowable value.\n", stderr);
        return 1;
    }

    tmp = n;
    while (tmp) {           /* sum digits for average */
        rem = tmp % 10;
        tot += rem;
        tmp /= 10;
        digits++;
    }
    avg = tot / digits;     /* calculate average */

    tmp = n;
    while (tmp) {           /* sum numbers higher than avg */
        rem = tmp % 10;
        if (rem > avg)
            big += rem;
        tmp /= 10;
    }

    printf ("sum of digits greater than avg : %d\n", big);
}

Nothing fancy, but 989 -> 18 , and 777 -> 0 and 778 -> 8 . Look things over and let me know if you have further questions.

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