华赛的一道面试题(关于char类型的)

源代码如下,找出代码中的错误。
#include "stdafx.h"

#include <stdio.h>
#include <iostream>
//using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{

unsigned char a1;
        a1=10;                               //Ascii码

while(a1>=0)
{
printf("%d\n",a1);
a1--;
}
system("PAUSE");
return 0;

}


好吧,哥当时蒙了,说10为int 的,赋值给char类型时候应该进行类型转换,后来面试官就没问我啥了,很明显是没搞懂char类型了。

现在一想,unsigned char是无符号型的,它的范围是0到255,只能为大于或等于0的数,a1永远大于等于0,所以这是一个死循环。

一般的给char赋值的确要加上单引号,如:

char chr = 'a' ; //当赋值你想要的字符时用单引号

这也等价于char chr=97; //此处为ascii码

 用printf("%d",chr)和printf("%c\n",chr)可以分别输出ascii和字符。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章