在`for`循环中遍历整个`unsigned char`范围 [英] Running through entire range of `unsigned char` in `for` loop

查看:890
本文介绍了在`for`循环中遍历整个`unsigned char`范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想遍历整个 unsigned char 范围的 for 循环。假设我想打印0到255之间的所有数字,我应该怎么做呢?



下面的代码是一个无限循环:

$ b $ unsigned char i = 0; i <= 255; i ++)
$ b

 我 ENDL; 

这个错过了0或255,取决于它是否是 i ++ ++ i

  for unsigned char i = 0; ++ i <= 255; i ++)
cout<<我 ENDL;

我可以在之前/之后放置一个cout for 循环来弥补缺失的条目,但我寻求一个更优雅的解决方案。

任何帮助将不胜感激! (,而 do-while 循环也很受欢迎!)

  unsigned char i = 0;解决方案


do {
cout<<我末日
}
while(++ i);

其他形式是你在条件被测试之前得到一个自由奔跑。这是一个重要的工具(如果不经常使用的话),在程序员的工具箱里。


I would like to run through the entire range of unsigned char in a for loop. Say I want to print all numbers from 0 to 255, how should I go about accomplishing that?

The following code would be an infinite loop:

for (unsigned char i=0; i<=255; i++)
    cout << i << endl;

This one misses out on 0 or 255, depending on whether it is i++ or ++i

for (unsigned char i=0; ++i<=255; i++)
    cout << i << endl;

I could place a cout before/after the for loop to compensate for the missing entry, but I seek a more elegant solution.

Any help would be greatly appreciated! (while and do-while loops are also welcomed!)

解决方案

Try,

unsigned char i = 0 ;
do {
  cout << i << endl ;
}
while ( ++i ) ;

The benefit of do .. while over the other forms is you get one free run before the condition is tested. This is an important tool for that reason (if only infrequently used), in a programmer's toolbox.

这篇关于在`for`循环中遍历整个`unsigned char`范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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