unsigned short i; unsigned short i; unsigned short index=0; unsigned long index=0; for(i = 0; i <index-1; i++) for(i=0; i<index-1; i++)
时间: 2024-01-04 19:04:03 浏览: 37
这两行代码的不同之处在于变量index的数据类型和i的循环条件。第一行代码中,index被声明为unsigned short类型,而第二行代码中,index被声明为unsigned long类型。此外,第一行代码中,i的循环条件是i < index-1,而第二行代码中,i的循环条件是i < index-1。由于unsigned short类型的范围比unsigned long类型小,因此第二行代码中的循环条件可能会导致溢出错误。同时,如果index的值过大,可能会导致第一行代码中的循环条件也出现溢出错误。因此,在选择变量类型和循环条件时应该根据具体情况进行权衡和考虑。
相关问题
unsigned short i; unsigned short index=0; for(i = 0; i <index-1; i++)
这段代码中存在两个问题:
1. 变量index的初始值是0,循环条件是i < index-1,因此循环体不会执行。如果index的值在循环之后被修改,那么循环体仍然不会执行。
2. 变量i的类型是unsigned short,如果i等于0时,i-1会产生一个非常大的正整数(unsigned short类型的溢出),导致循环条件始终成立,从而导致死循环。
可能的修正方法是将循环条件改为i < index,并且在循环之前确保index的值已经被正确设置。
为什么 unsigned short i=65538,输出i等于2
因为 unsigned short 的取值范围是 0 到 65535,当 i 赋值为 65538 时,超出了范围。在这种情况下,会发生截断(truncation),即只保留最低 16 位,即 65538 的二进制表示为 0000 0000 0000 0001 0000 0010,截断后只剩下后面的 16 位 0000 0001 0000 0010,对应的十进制数为 2。因此,输出 i 的值为 2。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)