ido91198
ido91198

Reputation: 87

Is there a problem with this code? Sometimes I get the correct answer and sometimes a really big number

Sometimes I get the right answer, like when I enter 87 and 3 it gives me back 261, but when I exit the program and re-run it, sometimes it returns45481185383493847891312640.000000`, or some other crazy number.

#include <stdio.h>

int main() {
    float pts = 0;
    float avg;
    float grade;
    float total;
    int f = 1;

    while (f == 1) {
        printf("Choose a Course Grade, and the amount of points that the course is worth: \n"
               "Enter -1 at the beginning if you want to exit\n");
        scanf("%f %f", &grade, &avg);
        if (grade == -1) {
            break;
        }
        pts += avg;
        total += (avg * grade);
        printf("%f\n", total);
    }
    printf("%f\n", (total / pts));
}

Upvotes: 0

Views: 70

Answers (1)

chqrlie
chqrlie

Reputation: 144695

The program has undefined behavior because the local variable total is uninitialized.

Initialize it to 0 and test the return value of scanf() to avoid undefined behavior, which explains your observations.

Here is a corrected version:

#include <stdio.h>

int main() {
    float pts = 0.0;
    float total = 0.0;
    float avg;
    float grade;

    for (;;) {
        printf("Enter a Course Grade or -1 to exit: ");
        if (scanf("%f", &grade) != 1 || grade == -1)
            break;
        printf("Enter a the amount of points that the course is worth: ");
        if (scanf("%f", &avg) != 1)
            break
        pts += avg;
        total += avg * grade;
        printf("%f\n", total);
    }
    printf("%f\n", total / pts);
    return 0;
}

Upvotes: 3

Related Questions