1.進制之間的轉換
%d 十進制輸出
%0x 十六進制輸出
%08x 十六進制輸出,輸出8位,如果不夠,補0
編程題:將十進制的數字轉換成n進制的數字
#include <iostream>
#include <stack>
using namespace std;
//使用stack,將得到的數字壓棧,最後逐一出棧
void MyTenToN1(int num, int n)//n表示進制
{
if(num < 0)
return;
else if(0 == num)
{
cout<<"0"<<endl;
return;
}
stack<int> st;
int i = 0;//餘數
int j = num;//商
while(j != 0)//商爲0是循環結束條件
{
i = j % n;
j = j / n;
st.push(i);
}
while(!st.empty())
{
cout<<st.top();
st.pop();
}
cout<<endl;
}
//每次得到最小位的數,乘位的權重
int MyTenToN2(int num, int n)
{
if(num < 0)
return -1;
else if(0 == num)
{
cout<<"0"<<endl;
return -1;
}
int i = 0;//餘數
int j = num;//商
int count = 0;
int result = 0;
int pow = 1;
while(j != 0)
{
i = j % n;
j = j / n;
++count;
if(count != 1)
{
pow *= 10;
}
result += i*pow;
}
return result;
}
int main()
{
cout<<MyTenToN1(123,2)<<endl;
cout<<MyTenToN1(123,3)<<endl;
cout<<MyTenToN1(123,4)<<endl;
cout<<MyTenToN1(123,5)<<endl;
cout<<MyTenToN1(123,6)<<endl;
cout<<MyTenToN1(123,7)<<endl;
cout<<MyTenToN1(123,8)<<endl;
cout<<MyTenToN1(123,9)<<endl;
cout<<MyTenToN2(123,2)<<endl;
cout<<MyTenToN2(123,3)<<endl;
cout<<MyTenToN2(123,4)<<endl;
cout<<MyTenToN2(123,5)<<endl;
cout<<MyTenToN2(123,6)<<endl;
cout<<MyTenToN2(123,7)<<endl;
cout<<MyTenToN2(123,8)<<endl;
cout<<MyTenToN2(123,9)<<endl;
return 0;
}
編程題:判斷當前字母是否爲大寫
#include <iostream>
using namespace std;
//由於字母的ASCII碼不一定連續,自己構建小寫字母連續的數組,進行比較
//引入頭文件#include<ctype.h> bool islower(int ch);是庫函數
bool Myislower(int ch)
{
int arr[] = {"abcdefghijklmnopqrstuvwxyz"};
int len = sizeof(arr)/sizeof(arr[0]);
for(int i=0; i<len-1; ++i)
{
if(arr[i] == ch)
{
return true;
}
}
return false;
}
int main()
{
cout<<Myislower('a')<<endl;
cout<<Myislower('c')<<endl;
cout<<Myislower('F')<<endl;
cout<<Myislower('G')<<endl;
cout<<Myislower('d')<<endl;
cout<<Myislower('R')<<endl;
return 0;
}
2.運算符的優先級
(1)/和% 不能除0,不能對0取餘,程序會崩潰
(2)%運算符的操作數必須是整數
(3)<<和>>位移運算符
左移,右邊補0 右移,左邊補符號位 一般先化成二進制再比較
(4)1<2<5 永真 要注意大於小於運算符的連續比較
(5)表達式1 && 表達式2 如果表達式1爲假,表達式2不計算 編譯器優化
表達式1 || 表達式2 如果表達式1爲真,表達式2不計算
3.變量的生存週期
4.switch…case 找到匹配的case進;顯示的碰到break出
switch不能用float類型的數,float類型的數不能用“==”直接比較
5.宏替換 做題的最好方法:把用到宏的地方都替換一下,重抄代碼計算結果
6.類型轉換
同類型,無符號的數比有符號的數寬 有符號—->無符號
算數運算時,整型(int)起
無符號左邊補0,有符號左邊補1
7.面試題:既然do…while能做的事while都可以做,爲什麼還要設計do…while?
答:(1)輔助定義複雜的宏,防止出現替換錯誤
#define SOMETHING fun1(); fun2()
if(a < 0)
SOMETHING;
實則執行:
if(a < 0)
fun1();
fun2();//fun2()始終會被執行
如果使用do…while
#define SOMETHING do{fun1(); fun2()}while(0)
if(a < 0)
SOMETHING;
實則執行:
if(a < 0)
do
{
fun1();
fun2();
}while(0);
(2)避免空宏引起的warming
內核中由於不同架構的限制,很多時候會用到空宏,在編譯的時候,空宏會給出warning,爲了避免這樣的warning,就可以使用do{}while(0)來定義宏。如:
#define SOMETHING do{}while(0)