Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Averaging program compiles but gives bad result

I was writing a C program that takes as many numbers as you want and finds the average of all of them. This was just something I was doin for fun and to test out how good I was doing so far into learning C. However, after debugging and compiling the program, I tested out the code and it didn’t work. I gave it the amount of numbers it would be working with and it gave a seemingly random number as output without even asking what the numbers were. The number it gave me is: 6422356. The code I wrote is below, do you know what might be causing this? I’m using notepad++ and MinGW compiler.

#include <stdio.h>

int main() {
    int nums;
    printf("Averagerator Machinerator! \n");
    printf("How many numbers are in this average? \n");
    scanf("%d", &nums);
    getchar();
    int whilst;
    int current[nums + 1];
    while (whilst ==! nums+1) {
        printf("A number, please: \n");
        scanf("%d", &current[whilst]);
        whilst = whilst + 1;
    };
    getchar();
    int average;
    int ncurrent;
    while (ncurrent ==! nums + 1) {
        average = average + current[ncurrent];
        ncurrent = ncurrent + 1;
    };
    getchar();
    printf("%d", average, "is your average. \n");
    getchar();
    return 0;
    
}

I tried to look in my program for possible issues, adding getchar()’s wherever necessary to test, and couldn’t find anything that might yield such a bizarre answer.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

while (whilst ==! nums+1) {

shouldn’t that be:

while (whilst != nums+1) {

What you are doing now is taking the boolean not of nums+1 and then trying to compare to whatever random value is in whilst.

BTW: You need to initialize those local variables with values or you will have some strange bugs.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading