如何实施圆形计数器? [英] How to implement a circular counter?

查看:96
本文介绍了如何实施圆形计数器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在C编程中创建一个循环计数器。第一个变量可以存储0-3的值。第二个变量询问用户的值(从0到3)。第三个变量要求用户向左或向右移动



如果剩下第三个变量,第二个变量应向左移动:



3-> 2

2-> 1

1-> 0

0-> 3

类似地,如果第三个变量是正确的,则第二个变量应向右移动:



0-> 1

1- > 2

2-> 3

3-> 0



我是什么已经尝试过:



ii已尝试过模数,但它不适用于边缘

I want to make a circular counter in C programming. First variable can store value from 0-3. Second variable asks the value from user (from 0-3). Third variable asks user to move either left or right

If third variable is left the second variable should move left:

3->2
2->1
1->0
0->3
Similarly if third variable is right the second variable should move right:

0->1
1->2
2->3
3->0

What I have tried:

ii have tried modulus ,but its not working on edges

推荐答案

引用:

ii已经尝试过模数,但它不能处理边缘

ii have tried modulus ,but its not working on edges



你只提 ......,但不是在边缘工作,但是你没有描述什么是无效的,即你期望的和你得到的。



我的猜测是,你没有得到0-> 3的正确值,因为你做了这样的事情:(0 - 1)%4 你和你xpect 3,但得-1。



为什么-1%4 == -1你可以在文献中找到,即Modulo操作 - 维基百科,免费的百科全书 [ ^ ]



对你来说,纠正这个问题的方法是:


You mention only "..., but ist not working in edges", but you don't describe what is not working i.e. what you expect and what you get.

My guess is, you don't get the right value for 0->3, because you make something like this: (0 - 1) % 4 and you expect 3, but get -1.

Why -1 % 4 == -1 you can find in the literature, i.e. Modulo operation - Wikipedia, the free encyclopedia[^]

For you the trick to correct this is:

const int cRange= 4;
int position;  // defined and set anywhere in your program..
int direction; // will be +1 or -1, defined and set anywhere in your program..
position= (Position + direction + cRange) % cRange;



最后位置== 0且方向为-1:

(0 - 1 + 4)%4 => 3

或位置= 3且方向为+ 1:

(3 + 1 + 4)%4 => 0

我希望它有所帮助。


Finally for Position == 0 and direction is -1:
(0 - 1 + 4) % 4 => 3
or Position = 3 and direction is + 1:
(3 + 1 + 4) % 4 => 0
I hope it helps.


这篇关于如何实施圆形计数器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆