#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
unsigned char n;
int total;
n = 50;
while(n-->0)
{
total += n;
}
return 0;
}
代码如上
变量n是无符号字符,当n为0时,进入循环,后执行n--,还是大于0,通过dev++调试,显示变成255,但是没进入循环,程序结束了,为什么呢?
while(n-->0)
改成
while(n-->=0)
就死循环了
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int n; // 使用有符号整数来表示 'n'
int total = 0; // 将 'total' 初始化为 0
n = 50;
while(n-- > 0) // 在这里使用前置递减
{
total += n;
}
printf("Total: %d\n", total);
return 0;
}
不知道你这个问题是否已经解决, 如果还没有解决的话:问题中的代码是一个简单的循环,当无符号字符变量n为0时,执行n--操作,然后判断条件n>0是否成立,如果成立就继续执行循环体,否则结束循环。在这个代码中,由于n是无符号字符变量,它的取值范围是0到255,所以当n为0时,执行n--操作之后,n的值会变为255。但是由于循环条件是n>0,所以循环条件不成立,循环体不会执行,所以程序就结束了。
如果你想让循环执行,可以修改代码中的循环条件为n>=0,这样即使n为0,经过n--操作后,n的值变为255,循环条件仍然成立,循环体会执行一次。以下是修改后的代码:
#include <stdio.h>
int main() {
unsigned char n = 0;
while (n >= 0) {
n--;
}
printf("n = %d\n", n);
return 0;
}
这样修改之后,循环体会执行一次,输出结果为n = 255。