Answered if statement condition checking

  • Thursday, March 29, 2012 7:13 AM
     
     

    hi,

    i have three variables

    float x,y,z,a,b,c;

    z = a * (b/c);

    if (z == 0.1)

    {

    y = 0.5x

    }

    else if (z ==0.5)

    {

    y = 1.5x

    }

    my doubt starts now............... my requirement is as follows.........

    if the result calculated from the expression for z as 0.25, how should i check my equation to calculate y;

    to which statement it goes..........

    its total confusion to me to explain this problem

    ppdev

All Replies

  • Thursday, March 29, 2012 8:40 AM
     
     

    i have three variables

    float x,y,z,a,b,c;

    6 actually!

    z = a * (b/c);
    if (z == 0.1)

    OK, the first thing to realise here is that you shouldn't test
    floating point values for equality - they're rarely ever equal because
    they're only ever approximately a value. Instead you should check
    they're within some range of the value.

    my doubt starts now............... my requirement is as follows.........
    if the result calculated from the expression for z as 0.25, how should i check my equation to calculate y;
    to which statement it goes..........

    It goes to none of the ones you've shown.

    Dave

  • Thursday, March 29, 2012 9:32 AM
     
      Has Code
    // test.cpp : Defines the entry point for the console application.
    //
    #include "stdafx.h"
    #include "iostream.h"
    int main(int argc, char* argv[])
    {
    	printf("Hello World!\n");
    	
    	float a,b,c,x,y,z;
    //	cin >> a >> b >> c >> x ;
    	printf("\n enter the values z and x are:\n");
    	
    	cin >> z >> x ;
    //	z= a * b / c;
    	printf("\n the values z and x are:\n");
    	cout << z << " " << x << " ";
    	if(z < 0.25)
    //	if(z == 0.1)
    	{
    		if(z<0)
    		{
    			printf("\n the z value is not in the range of 0 to 0.25\n");
    		}
    		else
    		{
    		y = 0.1 * x;
    		}
    	}
    	else if(z == 0.25 || z <= 0.5)
    	{
    		y = 0.5 * x;
    	}
    	else
    	{
    		printf("\n enter valid data\n");
    	}
    	cout << y <<" " << x << " " << z ;
    	
    	return 0;
    }

    i tried like this can u suggest me is it a good way to do this
  • Thursday, March 29, 2012 9:54 AM
     
     Answered

       else if(z == 0.25 || z <= 0.5)

    Presumably you intended 0.25 < z < 0.5?
    In fact you'd only need to have:

        else if ( z <= 0.5)

    since the earlier condition handled values < 0.25.

    i tried like this can u suggest me is it a good way to do this

    As I don't know what the requirement is, I don't know.

    Dave

    • Marked As Answer by ppdev Thursday, March 29, 2012 10:09 AM
    •