无符号整数与for循环的反向迭代 [英] Unsigned int reverse iteration with for loops

查看:123
本文介绍了无符号整数与for循环的反向迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个for循环中的迭代器变量作为 unsigned int 反向迭代为0,我不能想到一个类似的比较 i。 -1 ,如果它是一个 signed int

  for(unsigned int i = 10; i <= 10 ;-i){...} 

但这似乎很不清楚,因为它依赖于无符号整数的数字溢出高于10。 / p>

也许我只是没有一个清晰的头,但什么是更好的方法来做这个...



免责声明:这只是一个简单的用例,10的上限是微不足道的,它可以是任何东西, i code> unsigned int 。

解决方案

您可以使用

  for(unsigned int j = n; j--> 0;){} 

n-1 向下到 0


I want the iterator variable in a for loop to reverse iterate to 0 as an unsigned int, and I cannot think of a similar comparison to i > -1, as you would do if it was a signed int.

for (unsigned int i = 10; i <= 10; --i) { ... }

But this seems very unclear, as it is relying on the numerical overflow of the unsigned integer to be above 10.

Maybe I just don't have a clear head, but whats a better way to do this...

Disclaimer: this is just a simple use case, the upper limit of 10 is trivial, it could be anything, and i must be an unsigned int.

解决方案

You can use

for (unsigned int j = n; j-- > 0; ) {}

It iterates from n-1 down to 0.

这篇关于无符号整数与for循环的反向迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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