Jump to content

Need help still learning :)

#include<stdio.h>

float getDistance (float x)
{ float nDistance;    
float ObjectD;
float y;


y = x * 1230 * 1000.0/60.60/2;
return y;
}

int main()
{
    float ObjectD;
    int y, x;
    printf ("Enter amount of seconds" " ");
    scanf("%f", & ObjectD);
    x = getDistance(ObjectD);
    printf("%f", y);
    return 0;
    
}

 

 

 

I keep getting 0.000 as an answer any idea why? This is on C

Link to comment
https://linustechtips.com/topic/854220-need-help-still-learning/
Share on other sites

Link to post
Share on other sites

On 11/2/2017 at 8:54 AM, Radec said:

#include<stdio.h>

float getDistance (float x)
{ float nDistance;    
float ObjectD;
float y;


y = x * 1230 * 1000.0/60.60/2;
return y;
}

int main()
{
    float ObjectD;
    int y, x;
    printf ("Enter amount of seconds" " ");
    scanf("%f", & ObjectD);
    x = getDistance(ObjectD);
    printf("%f", y);
    return 0;
    
}

 

 

 

I keep getting 0.000 as an answer any idea why? This is on C

You never asign value to y in main function

Link to post
Share on other sites

On 02/11/2017 at 7:54 AM, Radec said:

x = getDistance(ObjectD);
printf("%f", y);

You assign the value to x and then print y, which is part of the reason its always 0.

Plus getDistance() returns a float, but you store it in an int, so its being made into 0.

 

Print out x instead, and change x to be a float and it should return the right value.

CPU: 6700k GPU: Zotac RTX 2070 S RAM: 16GB 3200MHz  SSD: 2x1TB M.2  Case: DAN Case A4

Link to post
Share on other sites

two things:

first: You have declared every variable as local. That means they are hidden from one method to another. So the Y that you return in the method getDistance() is totally different from the Y that you are trying to print. 

You have to set the returned value to Y if you want to print there the result.

 

Second: When you return a float value inside an int variable, the program eliminates all de fraction part with no approximation at all. 

So even if the returned value is 0.9999 The Integer result will show 0.

To fix it, you have to declare y, x as float in Main()

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×