Search code examples
cprintfscanfinteger-division

C Programming - Average


Okay I'm entirely stuck here and I do apologise if this inconviences you guys in any way but I need your help.

I'm currently learning C by myself and slowly getting there, started yesterday. So I thought I would give myself a task on having the user input 3 numbers and the program would have to find the average number between those three.

Here is my code:

#include <stdio.h>

int main() {

    int firstnum, secnum, thirnum, finalnum;

    printf("Enter the first number \n");
    scanf("%f",&firstnum);

    printf("Enter the second number \n");
    scanf("%s",&secnum);

    printf("Enter the third number \n");
    scanf("%t",&thirnum);

    finalnum = (firstnum +secnum+thirnum)/3;
    printf("The average value is: " finalnum);

return finalnum;

}

Solution

  • Reading integers or floats: Correct format specifier

    For integers you'll need %dand for doubles %lf. Read more about those elsewhere.

    E.g.

    scanf("%d",&firstnum);
    

    Printing integers or floats

    E.g.

    printf("The average value is: %d", finalnum);
    

    Avoid integer division: casting or all floats

    See http://mathworld.wolfram.com/IntegerDivision.html

    E.g.

    double finalnum = (firstnum +secnum+thirnum)/3.0;
    

    Or use floats for all types.

    double firstnum, secnum, thirnum, finalnum;
    

    Return 0 for success in main

    return 0;