華賽的一道面試題(關於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和字符。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章