1. 程式人生 > >C++ PRIMER PLUS 第六版程式設計答案(一)

C++ PRIMER PLUS 第六版程式設計答案(一)

2.6複習題

1.C++程式的模組叫什麼?

函式。

2.下面的前處理器編譯指令是做什麼用的?

#include<iostream>

該前處理器編譯指令將iostream檔案的內容新增到程式中。在編譯程式的時候自動執行

3.下面的語句是做什麼用的?

using namespace std;

using編譯指令使得std名稱空間的所有名稱都可以用

4.什麼語句可以用來列印短語”Hello,world”,然後開始新的一行?

std::cout<<”Hello,world\n”;

5.什麼語句可以用來建立名為cheeses的整數變數?

int cheeses;

6.什麼語句可以用來將值32賦給變數cheeses?

cheeses = 32;

7.什麼語句可以用來將從鍵盤輸入的值讀入變數cheeses中?

std::cin >> cheeses;

8.什麼語句可以用來列印”We have X varieties of cheese,”,其中X為變數cheeses的當前值.

std::cout << “We have” << cheeses << ” varieties of cheese,”;

9.下面的函式原型指出了關於函式的那些資訊?

int froop(double t);
void rattle(int n);
int prune(void);

第一個函式接受一個double值返回一個int值。第二個函式接受一個int值無返回值。第三個函式無接受值返回一個int值

10.定義函式時,在什麼情況下不必使用關鍵字return?

當函式的返回值為Void型別的時候。

11.假設您編寫的main()函式包含如下程式碼:cout<<”Please enter your PIN:”;而編譯器指出cout是一個未知識別符號.導致這種問題的原因很可能是什麼?指出3種修復這種問題的方法.

原因:沒有使用#include<iostream>。沒有使用using namespace std;。
修復:使用#include<iostream>。使用using namespace std;。使用std::cout<<"Please enter your PIN:";

2.7程式設計練習

1.編寫一個C++程式,它顯示您的姓名和地址。

#include <iostream>
using namespace std;

int main(){
    cout << "姓名:李文廣,地址:南京。"<<endl;
    system("pause");
}

2.編寫一個c++程式,它要求使用者輸入一個以long為單位的距離,然後將其轉換為碼(1:220碼)。

#include <iostream>
using namespace std;
int convert(int a){
    return a * 220;
}

int main(){
    int a;
    cin >> a;
    cout << convert(a) << endl;
    system("pause");
}

3.編寫一個c++程式,它使用3個使用者自定義的函式生成下面的輸出:

Three blind mice
Three blind mice
See how they run
See how they run

#include <iostream>
void fun1(void);
void fun2(void);

int main(){
    fun1();
    fun1();
    fun2();
    fun2();
    std::cin.get();
    return 0;
}

void fun1(){
    std::cout << "Three blind mice\n";
}

void fun2(){
    std::cout << "See how they run\n";
}

4.編寫一個程式,讓使用者輸入其年齡,然後顯示有多少個月。

#include <iostream>
using namespace std;
int fun1(int);

int main(){
    int month;
    cin >> month;
    cout << fun1(month) << endl;
    system("pause");
}

int fun1(int age){
    return age * 12;
}

5.編寫一個程式,其中main()呼叫一個使用者自定義的函式(以攝氏溫度值作為引數,並返回相應的華氏溫度值)。

#include <iostream>
using namespace std;
double fun1(double);

int main(){
    double a;
    cin >> a;
    cout << fun1(a) << endl;
    system("pause");
}

double fun1(double a){
    return 1.8*a + 32.0;
}

6編寫一個程式,其main()呼叫一個使用者自定義的函式(以光年值作為引數,並返回對應的天文單位的值)。

#include <iostream>
using namespace std;
int fun1(int);

int main(){
    double a;
    cin >> a;
    cout << fun1(a) << endl;
    system("pause");
}

int fun1(int a){
    return 63240 * a;
}

7編寫一個程式,要求使用者輸入小數數和分鐘數。在main()函式中,將這兩個值傳遞給一個void函式,後合併顯示時間。

#include <iostream>
using namespace std;
void fun1(int, int);

int main(){
    int a,b;
    cout << "Enter the number of hours: ";
    cin >> a;
    cout << "Enter the number of minutes: ";
    cin >> b;
    fun1(a, b);
    system("pause");
}

void fun1(int a, int b){
    cout << "Time:" << a << ":" << b;
}