简体   繁体   中英

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?

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 ;)

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);
  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.
}

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM