C Primer Plus(第6版)第九章複習題答案
阿新 • • 發佈:2019-01-25
9.10複習題
-
實際引數和形式引數的區別是什麼?
實際引數(actual argument)是指呼叫函式時傳遞給形式引數的值,形式引數(formal parameter)是指在函式定義時括號內的值,是本函式私有的區域性變數 -
根據下面各函式的描述,分別編寫它們的ANSI C函式頭。
注意只需要寫出函式頭,不用寫函式體
a. donut()接受一個int型別的引數,列印若干(引數指定數目)個 0 void donut(int num) b. gear()接受兩個int型別的引數,返回int型別的值 int gear(int a, int b) c. guess()不接受引數,返回一個int型別的值 int guess(void) d. stuff_it()接受一個double型別的值和double型別變數的地址,把第一個值儲存在指定位置 void stuff_it(double d, double * pd)
- 根據下面個函式的描述,分別編寫它們的ANSI C函式頭。注意,只需寫出函式頭,不用寫函式體。
a. n_to_char()接受一個int型別的引數,返回一個char型別的值 char n_to_char(int num) b. digit()接受一個double型別的引數和一個int型別的引數,返回一個int型別的值 int digit(double d, int i) c. which接受兩個可儲存double型別變數的地址,返回一個double型別的地址 double * which(double * pd1, double * pd2) d. random()不接受引數,返回一個int型別的值 int random(void)
- 設計一個函式,返回兩整數之和
//返回兩整數之和
int sum(int a, int b)
{
return a + b;
}
如果把複習題4改成返回兩個double型別的值之和,應如何修改函式?
double sum(double d1, double d2)
{
return d1 + d2;
}
設計一個名為alter()的函式,接受兩個int型別的變數x和y,把它們的值分別改成兩個變數之和兩變數之差。
注意:此題要使用指標
void change(int *x, int *y) { *x += *y; //利用數學關係,不用在建立temp來當作中轉站了 *y = *x - 2 *(* y); }
- 下面的函式定義是否正確?
// ANSI C之前可以這樣寫
void salami(num)
int num;
{
int count;
for (count = 1; count <= num; count++)
printf(" O salami mio ! \n");
}
// ANSI C後上述寫法也可以,但是會被廢除掉,還是用新的寫法
void salami(int num)
{
int count;
for (count = 1; count <= num; count++)
printf(" O salami mio ! \n");
}
- 編寫一個函式,返回3個整數引數中的最大值
// 使用了巢狀的條件表示式
int max(int a, int b, int c)
{
return c >= (a >= b ? a : b ) ? c : (a >= b ? a : b );
}
/*
給定下面的輸出:
Please choose one of the following:
1) copy files 2) move files
3) remove files 4)quit
Enter the number of your choice:
a. 編寫一個函式,顯示一個有4個選項的選單,提示使用者進行選擇(輸出如上所示)。
b. 編寫一個函式,接受兩個int型別的引數分別表示上限和下限。
該函式從使用者的輸入中讀取整數 。
如果超出上下限,函式再次列印選單(使用a的函式 )提示使用者輸入,然後獲取一個新值。
如果使用者輸入的整數在規定範圍內,
該函式則把整數返回給主調函式。如果使用者輸入一個非整數字符,該函式應該返回 4。
c. 使用本題a 和 b部分的函式編寫一個最小型程式。
最小型的意思是,該函式不需要實現選單中個選項的 功能,
只需顯示這些選項並獲取有效的響應即可。
*/
#include <stdio.h>
#define DOWN 3
#define UP 8
void menue(void);
int get_num(int down, int up);
void test(int num);
int main(void)
{
int tag;
menue();
tag = get_num(DOWN, UP);
test(tag);
return 0;
}
void menue(void)
{
printf("Please choose one of the following: \n");
printf("1) copy files 2) move files \n");
printf("3) remove files 4)quit \n");
printf("Enter the number of your choice: \n");
}
int get_num(int down, int up)
{
int num;
int state;
state = scanf("%d", &num);
while (state == 1 && (num < down || num > up))
{
menue();
printf("Please input the number %d to %d. \n", down, up);
state = scanf("%d", &num);
}
if (state != 1)
return 4;
}
void test(num)
{
switch (num)
{
case 1 :
printf("I will copy the file. \n");
break;
case 2 :
printf("I will move the file. \n");
break;
case 3 :
printf("I will remove the file. \n");
break;
case 4 :
printf("That's over now! Bye Bye! \n");
break;
default :
printf("No options you entered ! \n");
}
}