在C中查找char的最大值

use*_*828 5 c max char limit ansi-c

char通过简单的添加找到a的最大值,并在数字变为负数时进行测试:

#include<stdio.h>

/*find max value of char by adding*/
int main(){
  char c = 1;

  while(c + 1 > 0)
    ++c;

  printf("Max c = %d\n",(int)c);  /*outputs Max c = -128*/
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

while未来循环测试,所以第一次c+1是负的它打破了我们打印的价值c.但是,编程输出负数!

为什么这个程序不输出127

bgo*_*dst 5

在while条件中发生了隐式转换,这导致比较在int而不是chars上工作.

如果你改成它

while((char)(c + 1) > 0)
    ++c;
Run Code Online (Sandbox Code Playgroud)

那么它将打印127.

  • 正确......除了我认为正确的术语是"整数提升",而不是"隐式演员"......? (4认同)