C - Changing an integer to a float

0 Robert Summers · November 28, 2014
I need help as to why this is not working, I think it is because I have turned everything to a float from an integer the scanf function has changed so how can I get this to work.

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

int main()
{
    float avg;
    int num1;
    int num2;

    printf("Enter first number: \n");
    scanf("%d", &num1);

    printf("Enter second number: \n");
    scanf("%d", &num2);

    avg = ((float)num1 + (float)num2) / 2;

    printf("The average is: %.2f", avg);

    return 0;
}

Thanks for the help in return.

Post a Reply

Replies

Oldest  Newest  Rating
0 Mathias Frits Rørvik · November 28, 2014
//#include <stdlib.h> why are you including this?
#include <stdio.h>

int main(void)
{
    float avg;
    int num1;
    int num2;

    printf("Enter first number: ");
    scanf("%d", &num1);

    printf("Enter second number: ");
    scanf("%d", &num2);

    avg = (float) (num1 + num2) / (float) 2;

    printf("The average is: %.2f\n", avg);

    return 0;
}


You didn't cast the 2
  • 1

C

107,190 followers
About

One of the most popular languages of all time.

Links
Moderators
Bucky Roberts Administrator