0

I can't get this function to output the desired value of 0.07.

#include <stdio.h>
#include <cs50.h>
#include <math.h>

float i = 1.32;
float quar_val = 0.25;


int func(float val, float input)
{
    while (val < input)
    {
        input = input - val;
        printf("loop: %.02f\n", input);

    }
    printf("end loop: %.02f\n", input);
    return input;
}

int main(void)
{
    float x = func(quar_val, i);
    printf("end: %.02f\n", x);
}

here's the output i get:

loop: 1.07
loop: 0.82
loop: 0.57
loop: 0.32
loop: 0.07
end loop: 0.07
end: 0.00
1

It's the obvious problems that hide in plain sight! ;-) I'll bet it's returning 0 instead. Here's the problem:

int func(float val, float input)

The function is returning an int, not a float. Because the return type is designated as an int, it's converting the float to int (truncating the fractional part)before returning, and then main is casting it back to a float when assigning the value to x.

Try this:

float func(float val, float input)

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .