Converting int to float in C function

Viewed 146

So I have some source code that needs to be modified to include a 3rd mathematical formula.

The source code is:

#include <stdio.h>

int sum_and_diff (int a, int b, int *res)
{
    int sum;
    sum = a + b;
    *res = a – b;
    return sum;
}
int main (void)
{
    int b = 2;
    int diff;
    printf ("The sum of 5 and %d is %d\n", b,
        sum_and_diff (5, b, &diff));
    printf ("The difference of 5 and %d is %d\n", b, diff);
}

It needs to be modified by adding a division function and all arguments that pass through it should be converted to float.

This is what I have done so far, and for the life of me it will not work.

#include <stdio.h>
    
int sum_and_diff (int a, int b, int *res)
{
    int sum;
    sum = a + b;
    *res = a – b;
    return sum;
}
    
float div (float a, float b)
{
    float div;
    div = a / b;
    return div;
}
    
void main (void)
{
    float a = 5.0;
    int b = 2;
    int diff;
    float div;
    
    printf ("The sum of 5 and %d is %d\n", b,
        sum_and_diff (5, b, &diff));
    printf ("The difference of 5 and %d is %d\n", b,  diff);
    printf ("The quotient of %.0f and %d is %f\n", a, b, div);
}

Can someone please help me correct this, I have been at this for hours and just about every resource online says that you can't convert int to float in C.

Instead it compiles fine, but the 3rd print gives me a result of -nan.

1 Answers
float div;
// ...
printf ("The quotient of %.0f and %d is %f\n", a, b, div);

You declared a local variable called div which has no connection to the function named div (but shadows it). Then you print out the value of this variable, which was never initialized and therefore contains garbage, resulting in incorrect output or other undefined behavior.

You should delete the declaration float div; and instead call the function:

printf ("The quotient of %.0f and %d is %f\n", a, b, div(a,b));

Try it: https://onlinegdb.com/cw12CCTUH

Related