New In Programming
New In Programming

Reputation: 90

c# code for simple calculation

Could someone help me with the c# code. I want to calculate new a value- the value is calculated in the way: a=a-2*b, than to see if the result is less than zero and if it is in the range (0,a). I am usually doing that in few steps, but I have found a code on the internet which looks much better than mine, and the explanation of the problem the code solves is like mine, but I am not sure if the code is written in the proper way or not, because it doesn't give me the correct result. Also, there is no reported error in code.

 a = a - 2 * b < 0 ? 0 : a;

Is the code ok for the thing I need, or not?

Upvotes: 2

Views: 252

Answers (4)

Fabjan
Fabjan

Reputation: 13676

You may also want to use switch statement:

int newA = a - 2*b;
byte option = newA < 0 ? 0 : newA < A? 1 : 2;

switch(option)
{
  case 0 : // your code for NewA < 0  break;
  case 1 : // your code for NewA < A  break;
  case 2 : // your code for NewA > A  break;
}

Upvotes: 1

PartTimeIndie
PartTimeIndie

Reputation: 106

The code you posted could be written like this, maybe this helps clear things up:

        if (a - 2*b < 0)
        {
            a = 0;
        }
        else
        {
            //this assignment is not needed it is just here for clarification
            a = a;
        }

And btw i want to mention, it is not realy important how compact code is, it is most important how easy it is to read for you and others. So if you can read if else statements better then use them.

Oh well 2 slow ;)

Upvotes: 4

Richard
Richard

Reputation: 108975

 a = a - 2 * b < 0 ? 0 : a;

That is a shortcut for:

if (a - 2  * b < 0) {
  a = 0;
} else {
  // a = a is a no-op.
}

which does not seem to match your explanation.

I suspect you want:

var oldA = a;
a = a - 2*b;
if (a < 0) {
  // do something
} else if (a < oldA) {
  // do something else.
}

Upvotes: 1

Claudio P
Claudio P

Reputation: 2203

Your code is this:

int a;

if((a - 2 * b) < 0)
{
    a = 0;
}
else
{
    a = a;
}

Which doesn't make sense, because you set a = a. What i think you want is this:

a = (a - 2 * b) < 0 ? 0 : (a - 2 * b);

Upvotes: 3

Related Questions