double delay code for single variable two condition - c#

in my project, i need to code for X1 in such a way as
in local variables i declare and wrote the condition as
x1 = 0;
if(in1_w == 1)
{
x1 = 1;
}
if((in1_w == 1) && (in2_w == 1))
{
x1 = 2;
}
i's an microcontroller based in and out so, now i need to know how to right the delay code if x1=1 and x1=2. i have written as
for(k=0;k<=x1;k++)
{
delay_40sec();
}
but don't know how to write separately?
waiting for your kind help plz

You can use
System.Threading.Thread.Sleep(x)
where x is in milliseconds.
However be aware that it is not guaranteed to be accurate nor repeatable.

Related

C# - Stuck with use of list and array

I have been practicing c# nowadays and decided to write a code that converts any decimal to any base representation for practice purpose. And i have some troubles. Since i want to practice i decided to do it with an additional function where calculations take place. First i wanted to use an array to keep my result. But since ,at the beginning, i do not know the length of the array i could not define it.So i decided to use list(somehow i assumed undeclared slots are 0 as default). This is what i end up with.
class MainClass
{
static double number;
static double baseToConvert;
static int counter = 0;
static List<double> converted = new List<double>();
public static void Main(string[] args)
{
Console.WriteLine("Enter a decimal");
number = double.Parse(Console.ReadLine());
Console.WriteLine("Enter a base you want to convert to");
baseToConvert = double.Parse(Console.ReadLine());
ConverterToBase(number);
for (int i = converted.Count - 1; i >= 0; i--)
{
Console.WriteLine(converted[i]);
}
Console.ReadLine();
}
public static void ConverterToBase(double x)
{
double temp = x;
while (x >= baseToConvert)
{
x /= baseToConvert;
counter++;
}
converted[counter] = x;
counter = 0;
if (temp - x * Math.Pow(baseToConvert, Convert.ToDouble(counter)) >= baseToConvert)
{
ConverterToBase(temp - x * Math.Pow(baseToConvert, Convert.ToDouble(counter)));
}
else
{
converted[0] = temp - x * Math.Pow(baseToConvert, Convert.ToDouble(counter));
}
}
}
But after i write inputs console gets stuck without an error. My guess is that since i do not have any elements in the list " converted[counter] " does not make sense. But i do not know maybe the problem is somewhere else.
My question is not about the way i calculate the problem(Of course any suggestions are welcomed). I just want to know what i am doing wrong and how i can handle such situation(unknown array size , use of list , accessing a variable,array,.. etc from another method... ).
Thanks.
My previous answer was wrong as pointed out by #Rufus L. There is no infinite for loop. However upon further review, there seems to be an infinite recursion going on in your code in this line:
if (temp - x * Math.Pow(baseToConvert, Convert.ToDouble(counter)) >= baseToConvert)
{
ConverterToBase(temp - x * Math.Pow(baseToConvert, Convert.ToDouble(counter)));
}
ConverterToBase calls itself and there seems to be no base case nor return statement to end the recursion.
In the method named "ConverterToBase(double x)" you want to set value of 0 element. But you didn't add any element. The converted is Empty.
Firstly add value or values to your list.

Understanding IF Logic in my code

I thought I understood programming well enough to get the results I was looking for but alas this simply is not working for me. I've reduced my code to a simple Console application for assistance. The goal was to print out a 5x5 grid of 1's and 0's. Actually, I wanted to create a random x and y value such as 2 and 1 and I call this EmptyX and EmptyY. In this spot and only this spot, I should get a '0' printed. In all other cells there should be '1'. So it should be a grid of all 1's expect for the spot identified by EmptyX and EmptyY. My code below, although works, puts zero's down the entire column and row.
Why is this happening? I keep looking at my code and it seems my logic is good to me but of course it is not. How else can I make the grid with only a single 0 at the spot EmptyX and EmptyY?
class Program
{
static void Main(string[] args)
{
int EmptyX = new Random().Next(5);
int EmptyY = new Random().Next(5);
for (int y = 0; y < 5; y++)
{
for (int x = 0; x < 5; x++)
{
if ((x != EmptyX) && (y != EmptyY))
Console.Write("1");
else
Console.Write("0");
}
Console.WriteLine();
}
Console.ReadKey();
}
}
Something like this with the 2 and 1 example:
11111
11011
11111
11111
11111
The problem is you have confused AND and OR in the context of NOT. This is a very common logic error (as seen in this post).
If conditions, believe it or not, can mess up even experienced developers. I have seen it happen (never intentionally) over and over to senior developers who aren't paying attention. So, be reassured, you are not alone.
The best way to deal with complicated if conditions is to write Ridiculously Obvious Code (ROC) where you make the point of the logic ridiculously clear by using obvious naming and maybe being a bit verbose with the code. In most cases, drawing out the code a bit doesn't affect performance, because the compiler will optimize out the extra working variables and generate exactly the same IL.
So for example, instead of writing
if ((x != EmptyX) || (y != EmptyY)) //I fixed it for you
Console.Write("1");
else
Console.Write("0");
You could write something like
bool isOnEmptyColumn = (x == EmptyX);
bool isOnEmptyRow = (y == EmptyY);
bool isOnEmptyCell = isOnEmptyColumn && isOnEmptyRow;
if (isOnEmptyCell)
{
Console.Write("0");
}
else
{
Console.Write("1");
}
The above takes several lines more of code but is ridiculously obvious, and makes it much harder to goof up the combination of your logical operators.
If you find that the verbosity of the logic check makes your method too long, you can extract the logic to a separate function. In this example, I also use guard pattern to simplify the logic even further:
private bool IsOnEmptyCell(int x, int y)
{
if (x != EmptyX) return false;
if (y != EmptyY) return false;
return true;
}
//Main program
if (IsOnEmptyCell(x,y))
{
Console.Write("0");
}
else
{
Console.Write("1");
}
Again, rest assured this won't affect performance, as the compiler will automatically inline your code when necessary. The important thing is to focus on writing source code that is easy to understand and difficult to misunderstand.
your code will print 0 whenever
x=EmptyX or y=EmptyY
for example
if EmptyX =3 and EmptyY=3 and x=0 and y=3
if ((x != EmptyX) && (y != EmptyY))
if ((x != 3) && (y != 3))
if ((0 != 3) && (3 != 3))
if ((true) && (false))
if (false)
and it will not print '1' when it should.
change your condition to
if ((x != EmptyX) || (y != EmptyY))
Modify your if else condition.
Method-1.
if ((x == EmptyX) && (y == EmptyY))
Console.Write("0");
else
Console.Write("1");
Method-2.
if ((x != EmptyX) || (y != EmptyY))
System.out.print("1");
else
System.out.print("0");

Efficient Level up after every 10?

I'm trying to make it so that after every say 200 of a value, it will increase a global variable by 1. As you can see below the problem I have is that one, it isn't in any way shape or form efficient and really doesn't work well.
An overall of how I'd like this to work would be so that when GV.TotalNumberValue hits past a certain number, let's say 200, GV.TotalLevel will increase by one and update the text and this will happen every time that GV.TotalNumberValue increases by 200.
Finally, if this is going to be checking what the number is on constantly, should I have this bound to an event such as a button click or a timer? Your help's greatly appreciated, thanks.
void LevelMod()
{
if (GV.TotalNumberValue >= 200)
{
GV.TotalLevel = GV.TotalLevel + 1;
lblLevel.Text = string.Format("{0}{1}", GV.LevelPrefix, GV.TotalLevel);
}
else if (GV.TotalNumberValue >= 400)
{
GV.TotalLevel = GV.TotalLevel + 1;
lblLevel.Text = string.Format("{0}{1}", GV.LevelPrefix, GV.TotalLevel);
}
else
{
return;
}
}
Well, you can use simple math:
Either deduce the level from the value, like this:
int totalLevel = value / 200;
This works because an integer division is always rounded down.
Or, if you know that value has just been incremented, you can detect a level boundary like this:
bool shouldLevelUp = (value % 200) == 0;
if (shouldLevelUp)
++totalLevel;
Perhaps use integer division similar to:
void LevelMod()
{
// I assume the level variables are integrals, so perform an integer division
if (GV.TotalNumberValue / 200 > GV.TotalLevel)
{
GV.TotalLevel = GV.TotalNumberValue / 200;
lblLevel.Text = string.Format("{0}{1}", GV.LevelPrefix, GV.TotalLevel);
}
}
Essentially, your TotalLevel is always TotalNumberValue / 200. This assumes that that GV.TotalNumberValue is an integral type which always rounds the result towards zero.

Calling a boolean method inside the where clause of a Linq query

I've a query in Linq that calls a method inside the where clause...
Here's the code:
it = {my iter}
{
...
return from l in lifts
where(compare(l.Trip.Start, it.Start, startRadius))
select l;
}
private bool compare(POI a, POI b, int radius)
{
return (((b.Position.X.Value - radius < a.Position.X.Value)
&& (a.Position.X.Value < b.Position.X.Value + radius))
&& ((b.Position.Y.Value - radius < a.Position.Y.Value)
&& (a.Position.Y.Value< b.Position.Y.Value + radius)));
}
but the query returns every time all the lifts list. Why the method compare returns every time true?
Where I'm wrong?
Thank you
There has to be something wrong with your data or compare method.
There is nothing magical in how where works. I bet that if you place return false in compare method, returned list will be empty.
Update: you should consider #Jacob Proffitt answer too if you aren't sure of it.Start value at the time of query execution (I don't know why it is down-voted).
Try to replace LINQ query with simple foreach loop and step through code with debugger.
As suggested in comments, in compare method you probably want to measure if two points are within some range. So:
double x1 = a.Position.X.Value;
double y1 = a.Position.Y.Value;
double x2 = b.Position.X.Value;
double y2 = b.Position.Y.Value;
return ((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2)) < (r*r);

Use of unassigned local variable in C#

I am currently tasked with having a user enter in 5 variables. With the variables I need to create a series of loops to read the variables and assign them to variables. I am required to use only 1 Console.ReadLine(); I currently have this set up:
string userName = "";
int v1, v2, v3, v4, v5 = 0;
int i = 1;
while (i <= 5)
{
int InputCheck = 0;
Console.WriteLine("Please input a number {0} between 10 and 50;", i);
InputCheck = Convert.ToInt32(Console.ReadLine());
if (InputCheck >= 10 && InputCheck <= 50)
{
//if (i >= 10 && i <= 50)
//i++;
if (i == 1)
{
InputCheck = v1;
}
else if (i == 2)
{
InputCheck = v2;
}
else if (i == 3)
{
InputCheck = v3;
}
else if (i == 4)
{
InputCheck = v4;
}
else if (i == 5)
{
InputCheck = v5;
}
if (InputCheck < 10 || InputCheck > 50)
{
Console.WriteLine("The number you entered is either to high or to low please re-enter a number:");
}
}
I am confused as to why I'm getting the error Use of unassigned variables. Any help would be greatly appreciated.
You don't ever declare v1, v2, v3, etc. But assuming you declare them elsewhere, if I'm understanding what you're trying to do, your assignments are backwards.
For example, where you're writing
InputCheck = v1;
You probably want
v1 = InputCheck;
Then you could go through v1, v2, etc., and do what you want with the values (which would then be what the user typed for input).
Okay...after your recent comment, where you highlight that you initialize v1-5 elsewhere, I'm pretty sure your problem is that your assignments are just reversed, as I said above. If you need help understanding why, ask.
You declared the variables as
int v1, v2, v3, v4, v5 = 0;
This initializes v5 but not the others. The error message actually gave a clue to that. Reading the message is the first debugging tool, always.
The message told you "v1 is not initialized". So you go look at where you initialize it (or you aren't yet). This is how to find such a bug.
Actually, I knew that you had this problem with multiple variables in one declaration when you said you assigned 0 to them. The message allowed me to find the problem without even seeing your code.
Consider using a List to hold the numbers
var numbersList = new List<int>();
while(numbersList.Count <= 5)
{
int input = Convert.ToInt32(Console.ReadLine());
if(input >= 10 && input <= 50)
{
numbersList.Add(input);
continue;
}
Console.WriteLine("The number you entered is either to high or to low please re-enter a number:");
}
Are you initialising variables v1,v2,v3,v4,v5 ? Considering you did not initialised variables; you cannot assign unassigned variables to any other local variables, so declare variables v1,v2,v3,v4,v5 = 0 problem will be solved. As mentioned above Using Generic Lists is recommended.

Categories

Resources