Multiple "AND" conditions in a while loop c# - c#

Newbie and i´ve browsed for answers for a while but can´t seem to get it to work. I have a loop with two int variables that increase with different amount each loop depending on their set value before the loop starts. I want the loop to break and print the value of both ints when both of them have exceeded a set value. The problem i keep getting is that it seems like as soon as the first condition in both the "if" conditions and "while" conditions are met the So grateful if anyone could point out where I´m going wrong. Maybe this isn´t the best way to create this function?
Console.WriteLine("Please enter value1");
string strValue1 = Console.ReadLine();
int value1 = Convert.ToInt32(strValue1);
int value2 = 20;
do
{
if (value1 < 50 || value2 < 50)
{
Console.WriteLine("increase value 2 a little");
value2 = value2 + 10;
}
else
{
Console.WriteLine("increase value 2 a lot");
value2 = value2 + 30;
}
value1++;
}
while ((value2 < 200) && (value1 < 60));
Console.WriteLine("value1 is " + value1);
Console.WriteLine("value2 is " + value2);
Console.ReadKey();

Your loop condition tests both variables to be less than a certain threshold. As soon as one variable exceeds the threshold, the condition is no longer true. This is different from testing if both variables are above a certain threshold.
If you want the loop to exit only when both variables exceed the threshold, change the condition to use || (i.e. or): while (value2 < 200 || value1 < 60). Your condition tests the opposite ("both variables must be less"); but could be adapted to match your verbal description more closly: while (!(value2 >= 200 && value >= 60))
As a general rule of thumb: !(a && b) is equivalent to !a || !b. Same for !(a || b) is equivalent to !a && !b.

Related

BMI & BMR calculator

I'm trying to create a method that takes a user's height, weight, and age, and returns their BMI and BMR.
I think I've done this fine.
However, the last thing I need to do is add some validation to make sure the user has put in some sensible numbers. The constraints being applied to the input are:
50 [cm] ≤ height ≤ 220 [cm]
10 [kg] ≤ weight ≤ 250 [kg]
18 [years] ≤ age ≤ 70 [years]
To do this, I've tried using if statements
if (getHight >= 220 && getHight <= 50)
{
Console.WriteLine("Unfortunately, your input is incorrect, please try again");
}
else if (getAge >= 70 && getAge <= 18)
{
Console.WriteLine("Unfortunately, your input is incorrect, please try again");
}
else if (getWeight >= 250 && getWeight <= 10)
{
Console.WriteLine("Unfortunately, your input is incorrect, please try again");
}
However, regardless of what I ender, nothing shows up in the console by way of validation errors. It just outputs my BMI and BMR.
What am I missing here?
Your mistake is that you are using AND instead of OR.
You cannot both be taller than 220cm and shorter than 50cm.
Use OR operators instead of AND:
if (getHight > 220 || getHight < 50)
{
Console.WriteLine("Unfortunately, your input is incorrect, please try again");
}
else if (getAge > 70 || getAge < 18)
{
Console.WriteLine("Unfortunately, your input is incorrect, please try again");
}
else if (getWeight > 250 || getWeight < 10)
{
Console.WriteLine("Unfortunately, your input is incorrect, please try again");
}
Also as #PaulF mentioned, you should not be using <= and >= since the valid range of values is inclusive. Since your logic is the inverse (invalid values), you should drop the = and just use < and >.
As already mentioned, you should be using || instead of && when doing the comparisons and you should be using < and > since the boundary values are acceptable. You might spend some time reading up on the Boolean logical operators - AND, OR, NOT, XOR so they all make sense, because they're very common and used in just about every program you'll write.
I just wanted to add another possible solution in case you're doing a lot of these types of comparisons, which is to write an extension method for them. This way you only have to write it once, which reduces the chance of error.
Below I have an extension method that tests if a number is between a minimum and maximum value (along with an option to specify if those boundary values as valid). Note that I assumed you're testing with an int type, but you can change the type easily by changing the this int value to this double value or this float value, or whatever numeric type you're using:
public static class Extensions
{
public static bool IsBetween(this int value, int min, int max,
bool inclusive = true)
{
return inclusive ?
min <= value && value <= max:
min < value && value < max;
}
}
Now if you include that class in your project, we can use this method to test if the value is not between our accepted values by using the ! not operator. Also note that I changed the else if to separate if statements. This way, if there's more than one error, they all get reported at the same time and the user can correct them all at once. I also changed the error message so the user actually knows what's wrong and how to fix it:
// In your program class, not in the Extensions class above
if (!getHeight.IsBetween(50, 220))
{
Console.WriteLine("ERROR: Height must be an integer between 50 and 220");
}
if (!getAge.IsBetween(18, 70))
{
Console.WriteLine("ERROR: Age must be an integer between 18 and 70");
}
if (!getWeight.IsBetween(10, 250))
{
Console.WriteLine("ERROR: Weight must be an integer between 10 and 250");
}

How to update variable from with if statement MQL5

I have been googling for two days now, but can't figure this out and it seems to be basic.
Within the void OnTick(), I would like to create a variable int a;. Lets say it starts out with no value int a;, then I test condition if a is NULL or || equals 1 like this if (a == NULL || a == 1) which should always return true the first time the if statement runs due to NULL. I then assign a value to the variable a = 0;, so now a should equal 0.
This should trigger the else if(a == 0) the next time OnTick() is called, at this point I assign a = 1; resulting in the if being triggered next time round, etc and infinitum, constantly checking and assigning values switching between 0 and 1.
void OnTick()
int a;
if (PositionsTotal() < 1)
{
if(a == NULL || a == 1)
{
a = 0;
}
else if(a == 0)
{
a = 1;
}
}
I do not know what is going on, but during Testing in Strategy tester, I am getting a long string of numbers which switches between negatives and positives always with the same number -123456789 or 123456789, always 9 digits long.
Or during Debugging from Meta Editor. A random positive 3 digit number which never changes!
So far I have had both 303 and 597.
Beyond frustrating and most likely answered somewhere else.
Just not sure how to phrase the search term.
Thanks for you help.
I think the problem is that you declare your variable a inside the method OnTick, so it starts with an arbitrary value every time you call this method. Try declaring it outside this method.

Re-writing code to remove conditional statements

Is it possible to re-write the following so that it doesn't contain any conditional statements? I'm thinking there might be some clever trick using something like bitwise operations?
int a = // some value
int b = // some other value between 0 and max int
if(b >= 3)
{
return a + 1;
}
else
{
return a;
}
EDIT: to be clear, I'm not looking for a generic way of removing conditionals. I'm looking for a trick to remove the conditionals from this very specific code. Think of it as an academic puzzle.
To give an example, one way to remove conditionals (which happens to yield perf gains in some situations) is to precompute a lookup table and index into that with b instead. In this particular case this is tricky because b could be a very large number. Is there another way?
Here you go
return a - ((2 - b) >> 31);
Explanation:
r = 2 - b, < 0 (i.e. high bit set) for b >= 3
r >> 31, = -1 for b >= 3, 0 otherwise
uint a = // some value
uint b = // some other value between 0 and max int
bool c = b & 0xFFFC
return a + Convert.ToInt32(c);
The fastest will probably be as bitwise operations tend to be very fast
uint a = // some value
uint b = // some other value between 0 and max int
return (b & 0xFFFC) ? a+1 : a;
You could make it better by doing this:
int a = // some value
int b = // some other value between 0 and max int
return (b >= 3) ? (a+1) : a;
?: operator. (but yet it contains conditional statement.)
return b >= 3 ? a + 1 : a;
or
return a + (b >= 3 ? 1 : 0);
Is it possible to re-write the following so that it doesn't contain any conditional statements?
It is not possible to make it work out of no where. you must check this condition any way. There is no magic.
If you want to make your program faster by removing this condition then you picked wrong way. this is micro optimization.

C# Validation for specific input

I'm kinda new to this thread, but in short summary i'm having trouble with a small validation issue. Basically, i'm attempting to make a simple validation program that will collect a user's input and then determine if the input is valid in terms of, input being correctly implemented, the number being positive, and the number having to be either 0, 1, 2, 3, 4 or 5.
The overall program runs, but the issue i'm facing is every form of input is deemed an error, thus displaying my error statement, even if it is a valid input like 5 for example. I feel like there is a small mistake,i have made that is causing this, So is there any suggestions?
int user_input;
int count = 0;
do
{
Console.Write("\n\nUser Input:"
if ((int.TryParse(Console.ReadLine(), out user_input) == false)||(user_input < 0 || user_input != 0 ||user_input != 1 || user_input != 2
|| user_input != 3 || user_input != 4 || user_input != 5))
{
Console.WriteLine("Error : the action entered is not a valid number.");
count = 0;
}
else
count = 1;
Your mistake is because you use OR operator.
For example user print 3. In your statements one condition return false (input != 3), but all others return true.. That's why you always go into if condition..
You can use AND operator, but I can recommend you to simplify your condition. It will be more understandable and readable:
var count = 0;
do
{
Console.Write("\n\nUser Input:");
int user_input;
if ((int.TryParse(Console.ReadLine(), out user_input) == false) || (user_input < 0 || user_input > 5))
{
Console.WriteLine("Error : the action entered is not a valid number.");
count = 0;
}
else
count = 1;
}
while (count != 1);
You already got an answer about the problem with predicate logic. But you can even more simplify with linq like:
var count = (new string[]{"1","2","3","4","5"}).Contains(Console.ReadLine()) ? 1 : 0;

C# A loop using while. Variable displayed only once

I have a small problem. My code is this one :
int c = 0;
int i = 0;
int a = 28;
while (i < a) {
i++;
if (i % a == 0) {
c += i;
Console.WriteLine(i.ToString());
}
}
Why does the string i is displayed only once, after the end of the while ? It should be displayed a times.
Your help will be appreciated !
Your if condition is opposite it should be:
if (a % i == 0)
Currently you are trying to do remainder division with i % a and it will only meet the condition when i reaches 28, so you get the output once.
% is for modulus division, which basically divides by the number and gives you back the remainder. When you're loop reaches 28 it divides it by 28 and the resulting remainder is 0. This only happens once "when your loop reaches 28".
It would help if you told us what was printed out. I guess it is 28 because
i % a
returns the reminder of
i / a
(i divided by a) and it is only 0 when i is equal to a, i.e., 28.

Categories