Daniela Morais
Daniela Morais

Reputation: 2237

Wrong output in calculating average program

For years, I don't do anything in C and now I can't do simple things, I was accustomed to cin and cout and now Java. I was trying to make a simple program to calculate the average X amount of exams notes. The output are "random numbers" and checking to interrupt the program occurs before entering a note. Why is that?

#include <stdio.h>

int main(void) {
    int numeroDeNotas;
    float nota = 0.0;
    float notaAuxiliar = 0.0;
    char continuar;
    int media;

    do{
    printf("Enter the exam grade\n");
    scanf("%f", &notaAuxiliar);
    nota += (int) notaAuxiliar;
    numeroDeNotas++;
    printf("Do you want to continue? Enter n if you want to stop\n");
    scanf("%c", &continuar);
    }while(continuar != 'n');

    printf("%d\n\n", nota);
    printf("%d\n\n", numeroDeNotas);

    media = nota/numeroDeNotas;
    printf("Average grade: %d", media);
    return 0;
}

Upvotes: 1

Views: 95

Answers (3)

venkatesh kambakana
venkatesh kambakana

Reputation: 111

numeroDeNotas 

variable is declared but no where initialized. and you are incrementing in do while loop.

media = nota/numeroDeNotas;
printf("Average grade: %d", media);

and you are using garbage value to calculate media which is undefined output. initialize numeroDeNotas to zero.

Upvotes: 0

Aseda_gh
Aseda_gh

Reputation: 1

numeroDeNotas was declared with a variable type - float. So you can't use %d later in your code when writing a printf statement.

Upvotes: 0

rici
rici

Reputation: 241701

nota is a float, but you are using %d format code to print it. %d expects an int; you need %f to print floating point numbers.

C's standard I/O formatting is definitely not typesafe. When you provide a format code, you have to make sure the corresponding argument has the right type. However, if you had compiled with the -Wall option (at least, with gcc or clang), the compiler would have warned you.

Also, scanf("%c", &continuar); reads a single character without skipping whitespace, which will be the character immediately following the number read by scanf("%f", &notaAuxiliar);. That character is most likely a newline. You need to skip whitespace before reading the y or n, so you could use:

scanf(" %c", &continuar);

Upvotes: 3

Related Questions