I have a question about using 'while' in C#. I made a loop using 'while', but I don't know how to make it, and it did not print the last calculation.
Code:
if (obj.ControlCommand == 2)
{
try
{
while (obj.LiftHeight > sendMessage.LiftHeight)
{
sendMessage.LiftStatus = 12;
sendMessage.LiftHeight += 0.1f;
Thread.Sleep(1000);
if (sendMessage.LiftHeight >= obj.LiftHeight)
{
sendMessage.LiftStatus = 0;
sendMessage.LiftHeight = obj.LiftHeight;
}
}
When I set obj.LiftHeight to 2.95 for instance, it will increase 0.1 per sec.., but sendMessage.LiftHeight shown '... , 2.8, 2.9, 3.0, 2.95, 2.95 ... '. I want to make ' ..., 2.8, 2.9, 2.95, 2.95 ... ' What should I change to make it like that?
while (obj.LiftHeight < sendMessage.LiftHeight)
{
sendMessage.LiftStatus = 12;
sendMessage.LiftHeight -= 0.1f;
Thread.Sleep(1000);
if (sendMessage.LiftHeight <= obj.LiftHeight)
{
sendMessage.LiftStatus = 0;
sendMessage.LiftHeight = obj.LiftHeight;
}
}
For what I see, the problem lies in the place you are incrementing sendMessage.LiftHeight
. You should check whether it will go too high before incrementing. Change your code to
if (obj.ControlCommand == 2)
{
try
{
while (obj.LiftHeight > sendMessage.LiftHeight)
{
if (sendMessage.LiftHeight + 0.1f >= obj.LiftHeight)
{
sendMessage.LiftStatus = 0;
sendMessage.LiftHeight = obj.LiftHeight;
}
else
{
sendMessage.LiftStatus = 12;
sendMessage.LiftHeight += 0.1f;
Thread.Sleep(1000);
}
}
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.