Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

why its not correctly working?

+4 votes
asked Sep 15, 2023 by Атлашкiн Олександр (160 points)
#include <stdio.h>
#include <math.h>
#include <conio.h>

int main()

{
    float y;
    float x;
    printf("nubmer x \n");
    scanf("%f", &x);
    if(x<-1.5)
    {
        y=1;
    }
    
    else if(0)
    {
        y=0;
    }
    else if(x=-2)
    {
        y=0;
    }
else if(x>=1)
    {
        y=1;
    }

    else
        y=-2;
   
    printf("y=%f", y);
    getch();
    
}

2 Answers

+1 vote
answered Sep 15, 2023 by Peter Minarik (86,580 points)
edited Sep 15, 2023 by Peter Minarik

else if(0) always evaluates to false. Did you mean else if (x == 0)?

else if(x=-2) assigns the value -2 to x. Probably you want to check equality like else if (x == -2).

The x == -2 check must come before the x < -1.5 as -2 is less than -1.5, so the first condition will always be true and y will be set to 1.

Something like this would work:

#include <stdio.h>

int main()
{
    float y;
    float x;
    printf("Number x: ");
    scanf("%f", &x);
    
    if (x == -2.0f)
    {
        y = 0;
    }
    else if (x < -1.5f)
    {
        y = 1;
    }
    else if (x == 0.0f)
    {
        y = 0;
    }
    else if (x >= 1.0f)
    {
        y = 1;
    }
    else
    {
        y = -2;
    }
   
    printf("y = %f\n", y);
    return 0;
}
+2 votes
answered Sep 25, 2023 by Gulshan Negi (1,580 points)

Well, there are some logical issues with your code, you can try this code to fix the error.

#include <stdio.h>

#include <conio.h>
#include <math.h>

int main()

 {
    float y;
    float x;
    printf("number x \n");
    scanf("%f", &x);

    if (x < -1.5) 

{
        y = 1;
    } 

else if (x == -2) 

{
        y = 0;
    }

 else if (x >= 1) 

{
        y = 1;
    } 

else 

{
        y = -2;
    }

    printf("y = %f\n", y);

    return 0;
}

Thanks

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...