《C++編程思想》(第二版)第2章 C++中的C(筆記、習題及答案)(一),java編程思想習題答案

來源:互聯網
上載者:User

《C++編程思想》(第二版)第2章 C++中的C(筆記、習題及答案)(一),java編程思想習題答案

一.總結本章的內容:

1.如果聲明指標是void* ,它意味著任何類型的地址都可以間接引用那個指標(而如果聲明int*,則只能對int型變數的地址間接引用那個指標)。一旦我們間接引用一個void*,就會丟失關於類型的資訊。這意味著在使用前,必須轉換為正確的類型。

2.Static變數使得局部變數的值在程式的整個生命期裡仍然存在,其優點是在函數範圍之外它是停用,所以不可能被輕易改變。

3.內部連結意味著只對正在編譯的檔案建立空間,外部串連意味著所有被編譯過的檔案建立一片單獨的儲存空間。

4.顯示轉換文法:

(1).static_cast:用於“良性”和“適度良性”轉換,包括不用強制轉換(例如自動類型轉換);

(2).const_cast:對“const”和/或“volatile”進行轉換;

(3).reinterpret_cast:轉換為完全不同的意思。為了安全使用它,關鍵必須轉換回原來的類型。轉換成的類型一般只能用於位操作,否則就是為了其他隱秘的目的。這是所有轉換中最危險的。

(4).dynamic_cast:用於型別安全的向下轉換。

5.asm關鍵字:是一種轉義機制,允許在C++程式中寫彙編代碼。在組譯工具代碼中經常可以引用C++的變數,這意味著可以方便的和C++代碼通訊,且限定彙編代碼只能用於必要的高效調整,或使用特殊的處理器指令。

6.想給程式傳遞命令列參數時,C和C++的函數main()有特殊的參數表,其形式如:int main(int argc, char* argv[]);

   argv[0]是程式本身的路徑和名字。

7.複雜變數和函數定義:

(1).void *(*(*fp1)(int))[10];

      *fp1是一個指向函數的指標,該函數接受一個整型參數並返回一個指向含有10個void指標數組的指標。

(2).float (*(*fp2)(int,int,float))(int);

       *fp2是一個指向函數的指標,該函數接收三個參數(int、int和float)且返回一個指向函數的指標,該函數接受一個整型參數並返回一個float。

(3).typedef double (*(*(fp3)())[10])();

       fp3是一個指向函數的指標,該函數無參數,且返回一個含有10個指向函數指標數組的指標,這些函數不接受參數且返回double值。

(4).int (*(*f4())[10])();

       f4是一個返回指標的函數,該指標指向含有10個函數指標的數組,這些函數返回整型值。

二.和習題有關的函數:

     Ifthen.cpp

#include <iostream>using namespace std;int main(){int i;cout<<"type a number and 'Enter'"<<endl;cin>>i;if(i>5){cout<<"It's greater than 5"<<endl;}else{if(i<5){cout<<"It's less than 5"<<endl;}else{cout<<"It's equal to 5"<<endl;}}cout<<"type a number and 'Enter'"<<endl;cin>>i;if(i<10){if(i>5){cout<<"5<i<10"<<endl;}else{cout<<"i<=5"<<endl;}}else{cout<<"i>=10"<<endl;}return 0;}


Menu.cpp

#include <iostream>using namespace std;int main(){char c;while(true){cout<<"MAIN MENU:"<<endl;cout<<"l:left,r:right,q:quit->";cin>>c;if(c == 'q'){break;}if(c == 'l'){cout<<"LEFT MENU:"<<endl;cout<<"select a or b:";cin>>c;if(c == 'a'){cout<<"you choose 'a'"<<endl;continue;}if(c == 'b'){cout<<"you choose 'b'"<<endl;continue;}else{cout<<"you don't choose a or b"<<endl;continue;}}if(c == 'r'){cout<<"RIGHT MENU:"<<endl;cout<<"select c or d:";cin>>c;if(c == 'c'){cout<<"you choose 'c'"<<endl;continue;}if(c == 'd'){cout<<"you choose 'd'"<<endl;continue;}else{cout<<"you don't choose c or d"<<endl;continue;}}cout<<"you must type l or r or q!"<<endl;}cout<<"quitting menu..."<<endl;return 0;}


YourPets1.cpp

#include <iostream>using namespace std;int dog,cat,bird,fish;void f(int pet){cout<<"pet id number:"<<pet<<endl;}int main(){int i,j,k;}


YourPet2.cpp

#include <iostream>using namespace std;int dog,cat,bird,fish;void f(int pet){cout<<"pet id number:"<<pet<<endl;}int main(){int i,j,k;cout<<"f():"<<(long)&f<<endl;cout<<"dog:"<<(long)&dog<<endl;cout<<"cat:"<<(long)&cat<<endl;cout<<"bird:"<<(long)&bird<<endl;cout<<"fish:"<<(long)&fish<<endl;cout<<"i:"<<(long)&i<<endl;cout<<"j:"<<(long)&j<<endl;cout<<"k:"<<(long)&k<<endl;return 0;} 


Static.cpp

#include <iostream>using namespace std;void func(){static int i = 0;cout<<"i = "<<++i<<endl;}int main(){for(int x = 0;x < 10;x++){func();}return 0;}


FileStatic.cpp

#include <iostream>using namespace std;static int fs;int main(){fs = 1;}


FileStatic2.cpp

#include <iostream>using namespace std;extern int fs;int main(){fs = 100;}


Boolean.cpp

#include <iostream>using namespace std;int main(){int i,j;cout<<"Enter an integer:";cin>>i;cout<<"Enter another integer:";cin>>j;cout<<"i<j is"<<(i<j)<<endl;cout<<"i>=j is"<<(i>=j)<<endl;cout<<"i<=j is"<<(i<=j)<<endl;cout<<"i==j is"<<(i==j)<<endl;cout<<"i!=j is"<<(i!=j)<<endl;cout<<"i&&j is"<<(i&&j)<<endl;cout<<"i||j is"<<(i||j)<<endl;cout<<"(i<10)&&(j<10) is"<<((i<10)&&(j<10))<<endl;return 0;}


Bitwise.cpp

#include <iostream>using namespace std;#define PR(STR,EXPR) \cout<<STR; printBinary(EXPR); cout<<endl;int main(){unsigned int getval;unsigned char a,b;cout<<"Enter a number between 0 and 255:"<<endl;cin>>getval;a = getval;PR("a in binary:",a);cout<<"Enter a number between 0 and 255:"<<endl;cin>>getval;b = getval;PR("b in binary:",b);PR("a | b = ",a|b);PR("a & b = ",a&b);PR("a ^ b = ",a^b);PR("~a = ",~a);PR("~b = ",~b);unsigned char c = 0x5A;PR("c in binary: ",c);a |= c;PR("a |= c ;a =  ",a);b &= c;PR("b &= c ;b =  ",b);b ^= a;PR("b ^= a ;b =  ",b);return 0;}

Rotation.cpp

#include <iostream>using namespace std;unsigned char rol(unsigned char val){int highbit;if(val & 0x80){highbit = 1;}else{highbit = 0;}val<<=1;val |= highbit;return val;}unsigned char ror(unsigned char val){int lowbit;if(val & 1){lowbit = 1;}else{lowbit = 0;}val>>=1;val |= (lowbit<<7);return val;}


Union.cpp

#include <iostream>using namespace std;union Packed{char i;short j;int k;long l;float f;double d;};int main(){cout<<"aizeof(Packed) = "<<sizeof(Packed)<<endl;Packed x;x.i = 'c';cout<<x.i<<endl;x.d = 3.14159;cout<<x.d<<endl;return 0;}


StructArray.cpp

#include <iostream>using namespace std;typedef struct{int i,j,k;}ThreeDpoint;int main(){ThreeDpoint p[10];for(int i = 0;i < 10;i++){p[i].i = i+1;p[i].j = i+2;p[i].k = i+3;}return 0;}


ArrayAddresses.cpp

#include <iostream>using namespace std;int main(){int a[10];cout<<"sizeof(int) = "<<sizeof(int)<<endl;for(int i = 0;i < 10;i++){cout<<"&a["<<i<<"]="<<(long)&a[i]<<endl;}return 0;}


ArgsToInts.cpp

#include <iostream>#include <cstdlib>using namespace std;int main(int argc, char* argv[]){for(int  i = 1;i < argc;i++){cout<<atoi(argv[i])<<endl;}}


PointerIncrement2.cpp

#include <iostream>using namespace std;typedef struct{char c;short s;int i;long l;float f;double d;long double ld;}Primitives;int main(){Primitives p[10];Primitives* pp = p;cout<<"sizeof(Primitives) = "<<sizeof(Primitives)<<endl;cout<<"pp = "<<(long)pp<<endl;pp++;cout<<"pp = "<<(long)pp<<endl;return 0;}


PointerArithmetic.cpp

#include <iostream>using namespace std;#define P(EX) cout<<#EX<<":"<<EX<<endl;int main(){int a[10];for(int i = 0;i < 10;i++){a[i] = i;}int* ip = a;P(*ip);P(*++ip);P(*(ip+5));int* ip2 = ip+5;P(*ip2);P(*(ip2-4));P(*--ip2);P(ip2-ip);return 0;}


三.習題及答案


//: S03:Prototypes.h//  Declares various functionsvoid f(int);int g(float);float h(char);char k(void);  // same as char k()///:~//: S03:Prototypes.cpp {O}// Implements functions declared in Prototypes.h#include <iostream>using namespace std;void f(int i) {  cout << "f(" << i << ") returning void\n";}int g(float x) {  cout << "g(" << x << ") returning int\n";  return 0;}float h(char c) {  cout << "h(" << c << ") returning float\n";  return 1.5;}char k(void) {   // same as char k()  cout << "k() returning char\n";  return 'a';}

#include "Prototypes.h"int main() {  f(1);  g(1.5);  h('c');  k();}




方法一:

#include <iostream>#include <cmath>    // for sqrt()using namespace std;int main() {  const int MAX = 100;  // Print 2 as a prime:  cout << "2 ";  for (int i = 3; i <= MAX; i += 2)   {    float val = i; // Produce float value    int mid = static_cast<int>(sqrt(val));    int j;    for (j = 3; j <= mid; j += 2){      if (i % j == 0)  {        break;  }}    if (j > mid){      cout << i << ' ';}  }  cout << endl;  return 0;}

方法二:

#include <iostream>#include <cmath>    // for sqrt()using namespace std;#define MAX 100int main() {  cout<<"2";  for (int i = 3; i < MAX+1; i+=2)   {    for (int j = 3; j <= sqrt(i); j += 2){if (i % j == 0){break;}}if (j > sqrt(i)){cout << i << ' ';}  }  cout << endl;  return 0;}



#include <iostream>#include <string>#include <cstdio>int main() {    using namespace std;    string word;    for (;;) {        int code;        cin >> word;        if (word == "exit" | word == "return")            break;        // Map words:        if (word == "a" || word == "an" || word == "the")            code = 0;        else if (word == "after" || word == "before" ||                 word == "beside" || word == "by" ||                 word == "for" || word == "from" ||                 word == "in" || word == "into" ||                 word == "of" || word == "to")            code = 1;        else if (word == "if" || word == "else")            code = 2;        else if (word == "who" || word == "what" ||                 word == "when" || word == "where" ||                 word == "why")            code = 3;        else            code = 4;        // Print code description:        switch (code) {        case 0:            puts("article");            break;        case 1:            puts("preposition");            break;        case 2:            puts("conditional");            break;        case 3:            puts ("interrogative");            break;        default:            puts("unmapped word");            break;        }    }    return 0;} 



#include <iostream>using namespace std;int main(){char c;while(true){cout<<"MAIN MENU:"<<endl;cout<<"l:left,r:right,q:quit->";cin>>c;switch(c){case 'q':{break;}case 'l':{cout<<"LEFT MENU:"<<endl;cout<<"select a or b:";cin>>c;switch(c){case 'a':{cout<<"you choose 'a'"<<endl;continue;}case 'b':{cout<<"you choose 'b'"<<endl;continue;}default:{cout<<"you don't choose a or b"<<endl;continue;}}}case 'r':{cout<<"RIGHT MENU:"<<endl;cout<<"select c or d:";cin>>c;switch(c){case 'c':{cout<<"you choose 'c'"<<endl;continue;}case'd':{cout<<"you choose 'd'"<<endl;continue;}default:{cout<<"you don't choose c or d"<<endl;continue;}}}}cout<<"you must type l or r or q!"<<endl;}cout<<"quitting menu..."<<endl;return 0;}



#include <iostream>using namespace std;int main(){int X=1,Y=2,Z=3;cout<<"A = "<<X+Y-2/2+Z<<endl;cout<<"A = "<<X+(Y-2)/(2+Z)<<endl;return 0;}



#include <iostream>using namespace std;int dog;char cat;float bird;double fish;void f(int pet){cout<<"pet id number:"<<pet<<endl;}int main(){int i,j,k;cout<<"f():"<<(long)&f<<endl;cout<<"dog:"<<(long)&dog<<endl;cout<<"cat:"<<(long)&cat<<endl;cout<<"bird:"<<(long)&bird<<endl;cout<<"fish:"<<(long)&fish<<endl;cout<<"i:"<<(long)&i<<endl;cout<<"j:"<<(long)&j<<endl;cout<<"k:"<<(long)&k<<endl;return 0;} 

結果表示:


著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.