【问题标题】:C#, counter reset when a condition becomes trueC#,当条件为真时计数器重置
【发布时间】:2017-11-06 11:21:40
【问题描述】:

我有 2 个计数器,分别称为 a1count 和 b1count。 该部分代码用于控制步进电机。 每当电机驱动器返回 1 时,就意味着一个旋转周期已完成,并且 a1count 递增。 在循环期间,如果由于某种原因电机无法完成旋转(故障条件),驱动器返回 0,并且 b1count 递增。

现在我试图创建一个名为 c1count 的连续失败条件计数,如果假设 b1count 达到 10,它将弹出一个消息框。如果 c1count

这就是我现在拥有的:

public int a1count = 0;
public int b1count = 0;
public int c1count=0;

if (ethernetIPforSLCMicroCom1.Write("N7:70") == 1)
{    
    a1count += 1;        
}
else if (ethernetIPforSLCMicroCom1.Write("N7:70") == 0)
{                   
    b1count += 1;                   
}

   /* Im trying to create a consecutive fail condition count called c1count 
    which will pop-up a messagebox if say suppose b1count reaches 10. 
    If c1count <= 10 then a messagebox pops up notifying the error. 
    However, if in between those 10 counts, a1count is incremented then 
    I want to reset c1count to 0, ans start counting to 10 again if 
    b1count reaches 10 consecutively without a1count increment.*/

c1count = b1count;
if (c1count <= 10)
{                    
    MessageBox.Show("Consecutive Rejection Occured);
    ethernetIPforSLCMicroCom1.Write("B3:11/6", "1");                   
}

请帮忙!!

【问题讨论】:

  • 展示你的最小可行代码示例。这听起来有点基本,但它不可能给你答案
  • 您已经在问题中编写了程序的逻辑。在 c# 类中将其写为 //comments,然后将代码放在 cmets 下——我们使用我们本机思考的语言(例如英语)对复杂算法进行伪代码,然后翻译成 C#,因为它是明智的——就像在写论文之前先写论文计划论文
  • 不要在 cmets 中附加代码。查看该代码并告诉我们您是否认为它是可读的。请使用编辑功能并编辑您的问题
  • 您自己解释了:只要 a1count 增加,只需将 c1count 设置为 0。您在评论中的代码真的很难阅读,但它似乎并没有显示所需的代码。在你有循环的地方显示你的代码
  • 对不起...我已经编辑了主要问题。在 c1 达到 10 之前,一旦 a1 递增,我无法找到重置 c1 的方法。

标签: c# loops for-loop if-statement


【解决方案1】:

我不是很清楚你的意思是你想要这样吗?

public int a1count = 0;
public int b1count = 0;
public int c1count=0;

if (ethernetIPforSLCMicroCom1.Write("N7:70") == 1)
{    
    a1count++; 
    c1count = 0;   
}
else if (ethernetIPforSLCMicroCom1.Write("N7:70") == 0)
{                   
    b1count++;
    c1count++;                  
}


if (c1count > 0 && c1count <= 10)
{                    
    MessageBox.Show("Consecutive Rejection Occured);
    ethernetIPforSLCMicroCom1.Write("B3:11/6", "1");                   
}

【讨论】:

  • 请在这段代码中写下你在做什么。它将帮助更多的人理解这个答案,而不仅仅是提问的人。
  • 哈哈...完美。我不知道有这么简单的解决方案。从早上开始,我就一直在用 while 和 for 循环来实现这一点。谢谢弗拉基米尔拉扎尔。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-08
相关资源
最近更新 更多